2

Below I has a sample test case where I want to just grab the Saturday value if the word Blah appears before it. Below is what I got, but for some reason I end up getting "Blah" included. Any help would be great. Thanks!

Sub regex_practice()
Dim pstring As String

pstring = "foo" & vbCrLf & "Blah" & vbCrLf & vbCrLf & "Saturday"
'MsgBox pstring

Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")

With regex
    .Pattern = "(?:Blah)((.|\n)*)Saturday"
    .Global = True 'If False, would replace only first
End With


Set matches = regex.Execute(pstring)
Community
  • 1
  • 1
user60887
  • 225
  • 3
  • 9

1 Answers1

2

Of course. A non-capturing group is included in the overall match. What you might be looking for is to grab the appropriate capturing group here.
Change

With regex
    .Pattern = "(?:Blah)((.|\n)*)Saturday"
    .Global = True 'If False, would replace only first
End With

To

With regex
    .Pattern = "Blah[\s\S]*?(Saturday)"
    .Global = True 'If False, would replace only first
End With

Then use .SubMatches:

If regex.test(pstring) Then
    Set matches = regEx.Execute(pstring)
    GetSaturday = matches(0).SubMatches(0)
End If

Additionally ((.|\n)*) is rather bad, instead use e.g. [\s\S]*?.

Jan
  • 42,290
  • 8
  • 54
  • 79
  • 2
    `(.|\n)*` is not *rather* bad, it is horrible. Please do not even suggest it - unless it is ElasticSearch. A native ES5 construct that matches any char is `[^]`, by the way, but `[\s\S]` is fine. – Wiktor Stribiżew Oct 15 '17 at 19:42
  • Thanks! This really helps alot. And I got the (.|\n)* construct from here (2nd answer) with 190 upvotes lol. https://stackoverflow.com/questions/159118/how-do-i-match-any-character-across-multiple-lines-in-a-regular-expression – user60887 Oct 15 '17 at 20:06
  • @user60887: In the linked question it is: *Use the same approach as in JavaScript, `([\s\S]*)`.* Glad to help btw. – Jan Oct 15 '17 at 20:08