2011-09-25 4 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) 

는 나는 37 MSGBOX 할 다음 날 MSGBOX하지만 그것은 단지 나를 msgboxes.

답변

3

죄송합니다,이 답변이 Excel 용,하지만 어쩌면 그것은 바로 트랙에 당신을 넣어 도움이됩니다. VBA는 lookbehind를 지원하지 않지만, 상황을 감안할 때 원본의 부분 문자열을 사용하여이 작업을 수행 할 수있는 방법이 있습니다.

다음은 코드입니다. 가정 텍스트 셀 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

2 단계 정규식은 좋은 해결 방법입니다. 그리고'result '에 덧붙여지기 전에'seperator & .Item (i) .submatches.Item (j)'를 조합 할 때 좋은 점이 마음에 들었습니다. – brettdj

3

는이 같은 경기가 비 욕심 확인해야합니다 :

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

는 반환 : 37 'tymy_key ='나에게 – toop

+0

을 아, 내 충고에 실패 했어. 나는 나의 대답을 업데이트했다. –

+0

지금 막 반환합니다 : 37.하지만 아니요 – toop