[英]RegEx array / list / collection of all matches in VBA
I'm trying to use RegEx to get all instances of varying strings that exist in between a particular pair set of strings.我正在尝试使用 RegEx来获取存在于特定字符串对之间的不同字符串的所有实例。 Eg in the following string:
例如在以下字符串中:
"The Start. Hello. Jamie. Bye. The Middle. Hello. Sarah. Bye. The End"
I want to get a collection / array consisting of "Jamie"
and "Sarah"
by checking in between "Hello. "
and ". Bye. "
我想通过在
"Hello. "
和". Bye. "
之间签入来获得一个由"Jamie"
和"Sarah"
组成的集合/数组。
My RegEx object is working fine and I feel I'm nearly successful:我的 RegEx object 工作正常,我觉得我几乎成功了:
Sub Reggie()
Dim x As String: x = "The Start. Hello. Jamie. Bye. The Middle. Hello. Sarah. Bye. The End"
Dim regEx As RegExp
Set regEx = New RegExp
Dim rPat1 As String: rPat1 = "Hello. "
Dim rPat2 As String: rPat2 = " Bye."
Dim rPat3 As String: rPat3 = ".*"
With regEx
.Global = True
.ignorecase = True
.Pattern = "(^.*" & rPat1 & ")(" & rPat3 & ")(" & rPat2 & ".*)"
.MultiLine = True
' COMMAND HERE
End With
End Sub
But the last bit COMMAND HERE
I'm trying .replace(x, "$2")
which gives me a string of the last instance of a match ie Sarah
但是最后一点
COMMAND HERE
我正在尝试.replace(x, "$2")
这给了我一个匹配的最后一个实例的字符串,即Sarah
I've tried .Execute(x)
which gives me a MatchCollection
object and when browsing the immediate window I see that object only has the last instance of a match.我试过
.Execute(x)
,它给了我一个MatchCollection
object ,当浏览立即 window 时,我看到 object 只有最后一个匹配实例。
Is what I'm requiring possible and how?我所要求的是否可能以及如何?
That is because .*
matches as many any chars as possible and you should not match the whole string by adding .*
on both ends of your regular expression.这是因为
.*
匹配尽可能多的任何字符,并且您不应该通过在正则表达式的两端添加.*
来匹配整个字符串。
Besides, you need to escape special chars in the regex pattern, here, .
此外,您需要转义正则表达式模式中的特殊字符,在这里,
.
is special as it matches any char other than a line break char.很特别,因为它匹配除换行符以外的任何字符。
You need to fix your regex declaration like您需要修复您的正则表达式声明,例如
rPat1 = "Hello\. "
rPat2 = " Bye\."
rPat3 = ".*?"`
.Pattern = rPat1 & "(" & rPat3 & ")" & rPat2
Or, to further enhance the regex, you may或者,为了进一步增强正则表达式,您可以
\s*
(zero or more whitespaces) or \s+
(one or more whitespaces) to support any whitespace\s*
(零个或多个空格)或\s+
(一个或多个空格)替换文字空格以支持任何空格\W+
or \W*
.\W+
或\W*
匹配捕获字符串之后的任何非单词字符。rPat1 = "Hello\.\s*"
rPat2 = "\W+Bye\."
rPat3 = ".*?"`
.Pattern = rPat1 & "(" & rPat3 & ")" & rPat2
See the regex demo .请参阅正则表达式演示。 Details :
详情:
Hello\.
- Hello.
Hello.
string\s*
- zero or more whitespaces \s*
- 零个或多个空格(.*?)
- Group 1: any zero or more chars other than line break chars as few as possible (.*?)
- 第 1 组:除换行符之外的任何零个或多个字符尽可能少\W+
- one or more chars other than ASCII letters/digits/ _
\W+
- 一个或多个除 ASCII 字母/数字/ _
之外的字符Bye\.
- Bye.
Bye.
string.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.