Happy Culteur
Happy Culteur

Reputation: 21

Regex VbScript Capturing ahead

I have a text with this format:

[AAAAA]xyzxyzxyz
[AAAAA]abcdefghi
[AAAAA]whatever
[BBBBB]aaaaaaaa
[BBBBB]cccccccc
[BBBBB]dddddddd
[CCCCC]ffffffff
[CCCCC]eeeeeeee

I want to capture in a multiple selection the string after the label, without the label.

(?m)(?<=^\[BBBBBB\]).*$ 

To obtain an array with :

[1]aaaaaaaa
[2]cccccccc
[3]dddddddd

for example works fine on my editor , but Look ahead is not supported with Excel VBA (vbscript.regex)

The best i can do is :

 ((^\[BBBBBB\])(.*?)$) 

and replace the label by nothing in a 2nd step.

Does it exist a nice way to convert the : (?m)(?<=^[BBBBBB]).*$ to vba regex engine ?

Thank you for your help.

David.

Upvotes: 2

Views: 194

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626806

The positive lookbehind here is not necessary since its only purpose here is to define the left-hand context for the match you need, and there are no overlapping matches. Thus, you may safely use a consuming pattern instead, and enclose the rest of the pattern, or the part you are interested in, with capturing parentheses, to later grab the contents of Group 1.

Use

.Pattern = "^\[B{5}\]\s*([^\r\n]*)"

The . is better replaced with [^\r\n] to exclude the \r from the match, and {5} is a more convenient way to write 5 Bs.

Full demo:

Sub DemoFn2()
   Dim re As RegExp
   Dim s As String
   Dim colMatch As MatchCollection, objMatch As Match

s = "[AAAAA]xyzxyzxyz" & vbCrLf & "[AAAAA] abcdefghi" & vbCrLf & "[AAAAA] whatever" & vbCrLf & "[BBBBB] aaaaaaaa" & vbCrLf & "[BBBBB] cccccccc" & vbCrLf & "[BBBBB] dddddddd" & vbCrLf & "[CCCCC] ffffffff" & vbCrLf & "[CCCCC] eeeeeeee"
Set re = New RegExp
With re
  .Pattern = "^\[B{5}\]\s*([^\r\n]*)"
  .Global = True              ' Same as /g at the online tester
  .MultiLine = True          ' Same as /m at regex101.com
End With

Set colMatch = re.Execute(s)
For Each objMatch In colMatch
  Debug.Print objMatch.SubMatches.Item(0)
Next
End Sub

Upvotes: 2

Related Questions