加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式 – vba积极向前看太贪心了

发布时间:2020-12-14 06:26:06 所属栏目:百科 来源:网络整理
导读:我正在使用Access VBA解析带有正则表达式的字符串.这是我的正则表达式函数: Function regexSearch(pattern As String,source As String) As StringDim re As RegExpDim matches As MatchCollectionDim match As matchSet re = New RegExpre.IgnoreCase = Tr
我正在使用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”?

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

你想要的是匹配ungreedy.这可以通过放置一个?之后. :

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读