如何正确匹配? [英] How to match it correct way?
问题描述
我有一个 VBS 正则表达式代码
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?
推荐答案
应该返回括号中的内容,而不是括号后面的内容
what is in brackets should be returned, and not what is behind the brackets
由于您使用的是捕获组,因此您需要通过 .Submatches
:
Since you are using capturing groups, you need to access those captured texts via .Submatches
:
执行正则表达式时,当子表达式包含在捕获括号中时,可能会产生零个或多个子匹配.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.
您需要访问第一个 Submatches
元素,并使用 rain\s*(.*)
正则表达式.
You need to access the first Submatches
element, and use rain\s*(.*)
regex.
请参阅此处的正则表达式演示.
这里是脚本修复:
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
这篇关于如何正确匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!