【问题标题】:regex (vba) - repeat a pattern正则表达式 (vba) - 重复一个模式
【发布时间】:2011-11-24 12:23:00
【问题描述】:

我的代码是:

Dim regEx, retVal
' Create regular expression.
set text = "update my_table      set time4 = sysdate,      randfield7 = 'FAeKE',      randfield3 = 'MyE',      the_field9 = 'test'      WHERE my_key = '37',             tymy_key = 'me';"
Set regEx = CreateObject("vbscript.regexp")
regEx.pattern = ".+where.+ \'(.+)\'+.*;"
regEx.IgnoreCase = True
regEx.MultiLine = True
regEx.Global = True

Set objRegexMC = regEx.Execute(text)
MsgBox objRegexMC(0).SubMatches(0)

我希望它发送到 msgbox 37,然后发送到 msgbox 我,但它只发送 msgboxes 我。

【问题讨论】:

    标签: regex vba


    【解决方案1】:

    抱歉,此答案适用于 Excel,但也许它会帮助您走上正轨。 VBA 不支持lookbehind,但是根据您的情况,有一种方法可以做到这一点(使用原始的子字符串)。

    这里是代码。假设文本在单元格 A1 中,您要写的内容如下:

    =RegexExtract(RegexExtract(A1,"WHERE(.+)"),"\'(\w+)\'")
    

    它会产生结果:“37, me

    Function RegexExtract(ByVal text As String, _
                          ByVal extract_what As String, _
                          Optional seperator As String = ", ") As String
    
    Application.ScreenUpdating = False
    Dim i As Long, j As Long
    Dim result As String
    Dim allMatches As Object, RE As Object
    Set RE = CreateObject("vbscript.regexp")
    
    RE.Pattern = extract_what
    RE.Global = True
    Set allMatches = RE.Execute(text)
    
    With allMatches
    For i = 0 To .Count - 1
        For j = 0 To .Item(j).submatches.Count - 1
            result = result & (seperator & .Item(i).submatches.Item(j))
        Next
    Next
    End With
    
    If Len(result) <> 0 Then
        result = Right$(result, Len(result) - Len(seperator))
    End If
    
    RegexExtract = result
    Application.ScreenUpdating = True
    
    End Function
    

    【讨论】:

    • 两阶段正则表达式是一个很好的解决方法。我喜欢在附加到 result 之前结合 seperator &amp; .Item(i).submatches.Item(j) 的美妙感觉
    【解决方案2】:

    你需要使匹配不贪心,像这样:

    regEx.pattern = "where.+?\'(.+?)\'.+?\'(.+?)\'"
    

    【讨论】:

    • 返回:37' tymy_key = 'me
    • 很难确定您要查找的内容。。字符串text 会改变多少?期望什么类型的格式?我的意思是,你为什么不把 MsgBox 硬编码为 '37' 和 'me' 呢?我更新了我的答案。
    • 我正在尝试提取出现在 WHERE 之后的引号之间的每个值。
    • 由于 WHERE 之后可能有可变数量的引用值,是否有正则表达式可以用于未知数量的引用值?
    • 您需要一个支持可变长度正向回溯的正则表达式引擎。我建议首先创建一个包含您要查找的值的子字符串,然后对其进行解析。
    猜你喜欢
    • 1970-01-01
    • 2012-01-14
    • 2016-11-16
    • 2016-01-11
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    相关资源
    最近更新 更多