正则表达式:匹配 Excel Visual Basic 应用程序 (VBA) 函数(marco、模块)中两个字符串之间的字符串。 (正则表达式)
Regex: match string between two strings within an Excel Visiual Basic application (VBA) function (marco, module). (regular expression)
我确实有这个很棒的正则表达式:(?<=, )(.*)(?= \()
,它匹配“,”和“(”之间的任何字符。
例如。从以下字符串中,它与突出显示的文本相匹配:“Hey man, my regex is Super (Mega) Cool
(SC)”。我在各种正则表达式测试器中进行了测试(例如 https://extendsclass.com/regex-tester.html#ruby)。
但是,当在 Excel VBA 模块中使用它来创建我自己的函数时,它不起作用(见下文)。
Function extrCountryN(cellRef) As String
Dim RE As Object, MC As Object, M As Object
Dim sTemp As Variant
Const sPat As String = "((?<=, )(.*)(?= \())"
Set RE = CreateObject("vbscript.regexp")
With RE
.Global = True
.MultiLine = True
.Pattern = sPat
If .Test(cellRef) Then
Set MC = .Execute(cellRef)
For Each M In MC
sTemp = sTemp & ", " & M.SubMatches(0)
Next M
End If
End With
extrCountryN = Mid(sTemp, 3)
End Function
'https://extendsclass.com/regex-tester.html
在同一个模块中尝试类似的正则表达式非常适合我,例如^(.*?)(?= \()
成功匹配第一个“(”之前的所有内容。
如何修复它?
由于 VBA 正则表达式引擎不支持后向断言,您可以将其删除并改用消费模式。在这种情况下很简单,因为您实际上只在代码中使用捕获的值(使用 M.SubMatches(0)
)。
所以,快速修复是
Const sPat As String = ", (.*)(?= \()"
如果您需要处理制表符或 space 或任何白色 space,您需要 \s
而不是文字 space:
Const sPat As String = ",\s+(.*)(?=\s\()"
详情:
,
- 逗号
\s+
- 一个或多个白色spaces
(.*)
- 第 1 组:除换行字符外的任何零个或多个字符尽可能多
(?=\s\()
- 匹配紧跟白色 space 和 (
字符的位置的正前瞻。
查看演示截图:
我确实有这个很棒的正则表达式:(?<=, )(.*)(?= \()
,它匹配“,”和“(”之间的任何字符。
例如。从以下字符串中,它与突出显示的文本相匹配:“Hey man, my regex is Super (Mega) Cool
(SC)”。我在各种正则表达式测试器中进行了测试(例如 https://extendsclass.com/regex-tester.html#ruby)。
但是,当在 Excel VBA 模块中使用它来创建我自己的函数时,它不起作用(见下文)。
Function extrCountryN(cellRef) As String
Dim RE As Object, MC As Object, M As Object
Dim sTemp As Variant
Const sPat As String = "((?<=, )(.*)(?= \())"
Set RE = CreateObject("vbscript.regexp")
With RE
.Global = True
.MultiLine = True
.Pattern = sPat
If .Test(cellRef) Then
Set MC = .Execute(cellRef)
For Each M In MC
sTemp = sTemp & ", " & M.SubMatches(0)
Next M
End If
End With
extrCountryN = Mid(sTemp, 3)
End Function
'https://extendsclass.com/regex-tester.html
在同一个模块中尝试类似的正则表达式非常适合我,例如^(.*?)(?= \()
成功匹配第一个“(”之前的所有内容。
如何修复它?
由于 VBA 正则表达式引擎不支持后向断言,您可以将其删除并改用消费模式。在这种情况下很简单,因为您实际上只在代码中使用捕获的值(使用 M.SubMatches(0)
)。
所以,快速修复是
Const sPat As String = ", (.*)(?= \()"
如果您需要处理制表符或 space 或任何白色 space,您需要 \s
而不是文字 space:
Const sPat As String = ",\s+(.*)(?=\s\()"
详情:
,
- 逗号\s+
- 一个或多个白色spaces(.*)
- 第 1 组:除换行字符外的任何零个或多个字符尽可能多(?=\s\()
- 匹配紧跟白色 space 和(
字符的位置的正前瞻。
查看演示截图: