2011-09-28 60 views
8

我正在使用Access VBA解析正則表達式的字符串。這是我的正則表達式功能:vba積極lookahead太貪婪

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

我期待得到:

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 

當我測試它

153 

,因爲這和第一個實例之間唯一的字符'MP'是在前視中指定的類中的那些。

,但我實際的返回值是:

153 - MP 13.61 to 

爲什麼捕捉到第二個「MP」?

回答

12

因爲默認情況下.+是貪婪的。 .+吞噬每個字符,直到它遇到換行符或輸入結束。當發生這種情況時,它回溯到最後的MP(您的案例中的第二個)。

你想要的是匹配不知道。這可以通過將完成一個?.+

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

這解決了這個問題。 – sigil

+0

很高興聽到這個印記。 –

+0

+1很好地完成。 – brettdj