Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex vba正向前瞻太贪婪了_Regex_Vba - Fatal编程技术网

Regex vba正向前瞻太贪婪了

Regex vba正向前瞻太贪婪了,regex,vba,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 ma

我正在使用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”的第一个实例之间的唯一字符是在lookahead中指定的类中的字符

但我的实际返回值是:

153 - MP 13.61 to

为什么它最多捕获第二个“MP”?

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

你想要的是和ungreedy比赛。这可以通过在
+
之后放置
来完成:

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