如何为caputure只匹配部分匹配的字符串?非捕获组

问题描述:

下面我有一个示例测试用例,我只想抓住星期六值,如果单词Blah出现在它之前。下面是我得到的,但由于某种原因,我最终得到了“Blah”。任何帮助都会很棒。谢谢!如何为caputure只匹配部分匹配的字符串?非捕获组

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]*?

+2

'(。| \ n)*'不是*相当*不好,这太可怕了。请不要建议 - 除非它是ElasticSearch。顺便说一句,匹配任何字符的原生ES5结构是'[^]',但'[\ s \ S]'没问题。 –

+0

谢谢!这确实有助于很多。我从这里得到了(。| \ n)*结构(第二个答案),190个赞扬声。 https://stackoverflow.com/questions/159118/how-do-i-match-any-character-across-multiple-lines-in-a-regular-expression – user60887

+0

@ user60887:在链接的问题是:*使用与JavaScript相同的方法,'([\ s \ S] *)'。*很高兴帮助顺便说一句。 – Jan