2011-09-25 169 views
1

我的代码是:正则表达式(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我。

回答

3

对不起,这个答案是Excel中,但也许它会帮助把你在正确的轨道上。 VBA不支持向后看,但是你给出了情况,有一种方法可以做到这一点(使用原始的子字符串)。

这是代码。假设文本在单元格A1,这里就是你会写什么:

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

这将产生的结果: “37,我

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 
+0

两阶段正则表达式是一个很好的解决方法。我喜欢在将'seperator&.Item(i).submatches.Item(j)'结合到'result'之前, – brettdj

3

你需要让比赛非贪婪,就像这样:

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

返回:37' tymy_key =“我 – toop

+0

哎呀,我自己的建议失败了。我更新了我的答案。 –

+0

现在它只是返回:37.但是,没有我 – toop