VBA:子匹配正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13675735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA: Submatching regex
提问by John Jiang
I have the following code:
我有以下代码:
Dim results(1) As String
Dim RE As Object, REMatches As Object
Set RE = CreateObject("vbscript.regexp")
With RE
.MultiLine = False
.Global = True
.IgnoreCase = True
.Pattern = "(.*?)(\[(.*)\])?"
End With
Set REMatches = RE.Execute(str)
results(0) = REMatches(0).submatches(0)
results(1) = REMatches(0).submatches(2)
Basically if I pass in a string "Test" I want it to return an array where the first element is Test and the second element is blank.
基本上,如果我传入一个字符串“Test”,我希望它返回一个数组,其中第一个元素是 Test,第二个元素是空白。
If I pass in a string "Test [bar]", the first element should be "Test " and the second element should be "bar".
如果我传入一个字符串“Test [bar]”,第一个元素应该是“Test”,第二个元素应该是“bar”。
I can't seem to find any issues with my regex. What am I doing wrong?
我似乎找不到正则表达式的任何问题。我究竟做错了什么?
回答by Andrew Clark
You need to add beginning and end of string anchors to your regex:
您需要将字符串锚点的开头和结尾添加到正则表达式中:
...
.Pattern = "^(.*?)(\[(.*)\])?$"
...
Without these anchors, the .*?
will always match zero characters and since your group is optional it will never try to backtrack and match more.
如果没有这些锚点,.*?
将始终匹配零个字符,并且由于您的组是可选的,它永远不会尝试回溯和匹配更多。