下面我有一个示例测试用例,如果Blah出现在它之前,我想抓住星期六的值。以下是我得到的,但由于某种原因,我最终得到了“Blah”。任何帮助都会很棒。谢谢!
Sub regex_practice()
Dim pstring As String
pstring = "foo" & vbCrLf & "Blah" & vbCrLf & vbCrLf & "Saturday"
'MsgBox pstring
Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
With regex
.Pattern = "(?:Blah)((.|\n)*)Saturday"
.Global = True 'If False, would replace only first
End With
Set matches = regex.Execute(pstring)
答案 0 :(得分:2)
当然。整个匹配中包括非捕获组。您可能正在寻找的是在这里抓住适当的捕获组 变化
With regex
.Pattern = "(?:Blah)((.|\n)*)Saturday"
.Global = True 'If False, would replace only first
End With
要
With regex
.Pattern = "Blah[\s\S]*?(Saturday)"
.Global = True 'If False, would replace only first
End With
然后使用.SubMatches
:
If regex.test(pstring) Then
Set matches = regEx.Execute(pstring)
GetSaturday = matches(0).SubMatches(0)
End If
此外((.|\n)*)
相当糟糕,而是使用例如[\s\S]*?
。