vba积极向前看太贪心了

时间:2011-09-28 19:39:57

标签: regex vba

我正在使用Access VBA解析带有正则表达式的字符串。这是我的正则表达式函数:

Function regexSearch(pattern As String, source As String) As String

Dim re As RegExp
Dim matches As MatchCollection
Dim match As match


Set re = New RegExp
re.IgnoreCase = True

re.pattern = pattern
Set matches = re.Execute(source)


    If matches.Count > 0 Then
        regexSearch = matches(0).Value
    Else
        regexSearch = ""
    End If


End Function

当我用以下方法测试时:

regexSearch("^.+(?=[ _-]+mp)", "153 - MP 13.61 to MP 17.65")

我期待得到:

153

因为它和第一个'MP'实例之间的唯一字符是前瞻中指定的类中的字符。

但我的实际回报值是:

153 - MP 13.61 to

为什么它会捕捉到第二个“MP”?

1 个答案:

答案 0 :(得分:13)

因为默认情况下.+是贪婪的。 .+吞噬每个字符,直到遇到换行符或输入结束为止。当发生这种情况时,它会回溯到最后一个MP(在您的情况下是第二个)。

你想要的是匹配 ungreedy 。这可以通过在?之后放置.+来完成:

regexSearch("^.+?(?=[ _-]+MP)", "153 - MP 13.61 to MP 17.65")