2011-09-25 135 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