下面我有一个示例测试用例,如果“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)
最佳答案
当然。整场比赛包含非捕获组。您可能正在寻找的是在此处获取适当的捕获组。
改变
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]*?
.
关于regex - 如何仅捕获匹配字符串的一部分?非捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46758909/