2

I have a VBS regex code

    Dim re, targetString, colMatch, objMatch
Set re = New RegExp
With re
  .Pattern = "rain(.*)"
  .Global = True
  .IgnoreCase = True
End With
targetString = "The rain in Spain falls mainly in the plain"

Set colMatch = re.Execute(targetString)
For each objMatch  in colMatch
  wscript.echo objMatch.Value & "<br />"
Next

It returns "rain in Spain falls mainly in the plain" But I need the "in Spain falls mainly in the plain" to be returned" Usually what is in brackets should be returned, and not what is behind the brackets Which way to do it correct?

Alex
  • 193
  • 1
  • 3
  • 16

2 Answers2

4

what is in brackets should be returned, and not what is behind the brackets

Since you are using capturing groups, you need to access those captured texts via .Submatches:

When a regular expression is executed, zero or more submatches can result when subexpressions are enclosed in capturing parentheses. Each item in the SubMatches collection is the string found and captured by the regular expression.

You need to access the first Submatches element, and use rain\s*(.*) regex.

See the regex demo here.

And here is the script fix:

Dim re, targetString, colMatch, objMatch
Set re = New regexp
With re
  .pattern = "rain\s*(.*)"   ' <-- \s* will trim the start of the submatch
  .Global = True
  .IgnoreCase = True
End With
targetString = "The rain in Spain falls mainly in the plain"

Set colMatch = re.Execute(targetString)
For Each objMatch In colMatch
  wscript.echo objMatch.SubMatches.Item(0) & "<br />"  ' <--- We need to get the first submatch
Next
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

stribizhev is right, you need to get the submatches as follows:

objMatch.Item(0).Submatches(0)

lintmouse
  • 5,079
  • 8
  • 38
  • 54
  • Could you please give a working example. I tried to add wscript. echo objMatch.Item(0).Submatches(0) but it returns error – Alex Sep 29 '15 at 15:44