正则表达式(vba) - 重复一个模式

时间:2011-09-25 04:45:44

标签: regex vba

我的代码是:

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 me。

2 个答案:

答案 0 :(得分:3)

你需要让比赛变得非贪婪,如下所示:

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

答案 1 :(得分:3)

很抱歉,这个答案适用于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