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

标签 regex excel vba

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

相关文章:

excel - Access/Excel VBA - 跳过每个循环

javascript - 拆分值但将值保留在结果数组中

java - 使用replaceAll作为下标

java - 手机号码验证问题的正则表达式模式

regex - 帮助在 Linux 终端中使用正则表达式和 grep

Excel 求解器忽略 VBA 中的约束

vba - 为什么我的数组函数不起作用?

vba - 打印时如何启用订书机?

excel - 文本到列 - 具有不同空格数的统一响应

vba - Excel宏: make a recorded one less cell specifc?