gpt4 book ai didi

regex - 如何仅捕获匹配字符串的一部分?非捕获组

转载 作者:行者123 更新时间:2023-12-03 03:27:18 25 4
gpt4 key购买 nike

下面我有一个示例测试用例,如果“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com