如何防止完全匹配和仅匹配组

时间:2019-07-04 18:48:51

标签: regex vba

我想知道您如何停止使用正则表达式的完全比赛。

具有以下模式:

===(.+)[\r\n](.+)

和输入:

===Index Plate 20137-001.zoe ===Digi Erox 20137-001A.zoe

产生:

Full match: ===Index Plate 20137-001.zoe

Group 1: ===Index Plate

Group 2: 20137-001.zoe

Full match: ===Digi Erox 20137-001A.zoe

Group 1: ===Digi Erox

Group 2: 20137-001A.zoe

但是,我真的可以不用完全匹配而只匹配第1组和第2组。

即我只需要这个:

Group 1: ===Index Plate

Group 2: 20137-001.zoe

Group 1: ===Digi Erox

Group 2: 20137-001A.zoe

您如何使用正则表达式做到这一点?

1 个答案:

答案 0 :(得分:0)

正则表达式匹配始终是正则表达式匹配操作的强制性输出。捕获组是可选的,它们可能不存在。如果您定义捕获组以在特定上下文中获取字符串的一部分,请使用那些Submatches

Dim re As regExp
Dim testString As String, colMatch As MatchCollection, objMatch As Match

testString = "==Index Plate" & vbCrLf & "20137-001.zoe" & vbCrLf & "===Digi Erox" & vbCrLf & "20137-001A.zoe"
Set re = New regExp
With re
  .Pattern = "===(.+)[\r\n](.+)"
  .Global = True
End With

Set colMatch = re.Execute(testString)
For Each objMatch In colMatch
  Debug.Print objMatch.SubMatches(0)  ' <- Print Group 1 value only
  Debug.Print objMatch.SubMatches(1)  ' <- Print Group 2 value only
Next

输出:

enter image description here

注意:.与CR匹配,因此您可能要使用.Pattern = "===([^\r\n]+)[\r\n]+([^\r\n]+)"

相关问题