我有这样格式的文本:
[AAAAA]xyzxyzxyz
[AAAAA]abcdefghi
[AAAAA]whatever
[BBBBB]aaaaaaaa
[BBBBB]cccccccc
[BBBBB]dddddddd
[CCCCC]ffffffff
[CCCCC]eeeeeeee
我想在多选中捕获标签后的字符串,没有标签。
(?m)(?<=^\[BBBBBB\]).*$
要获得一个数组:
[1]aaaaaaaa
[2]cccccccc
[3]dddddddd
例如在我的编辑器上工作正常,但 Excel VBA (vbscript.regex) 不支持 Look ahead
我能做的最好的是:
((^\[BBBBBB\])(.*?)$)
并在第二步中用任何内容替换标签。
是否存在将 : (?m)(?<=^[BBBBBB]).*$ 转换为 vba 正则表达式引擎的好方法?
谢谢您的帮助。
大卫。
最佳答案
此处的正向后视不是必需的,因为它的唯一目的是为您需要的匹配定义左侧上下文,并且没有重叠匹配。因此,您可以安全地使用消费模式,并将模式的其余部分或您感兴趣的部分用捕获括号括起来,以便稍后获取第 1 组的内容。
利用
.Pattern = "^\[B{5}\]\s*([^\r\n]*)"
.
最好用 [^\r\n]
代替排除 \r
从比赛中,和{5}
是更方便的写法 5 B
s。完整演示:
Sub DemoFn2()
Dim re As RegExp
Dim s As String
Dim colMatch As MatchCollection, objMatch As Match
s = "[AAAAA]xyzxyzxyz" & vbCrLf & "[AAAAA] abcdefghi" & vbCrLf & "[AAAAA] whatever" & vbCrLf & "[BBBBB] aaaaaaaa" & vbCrLf & "[BBBBB] cccccccc" & vbCrLf & "[BBBBB] dddddddd" & vbCrLf & "[CCCCC] ffffffff" & vbCrLf & "[CCCCC] eeeeeeee"
Set re = New RegExp
With re
.Pattern = "^\[B{5}\]\s*([^\r\n]*)"
.Global = True ' Same as /g at the online tester
.MultiLine = True ' Same as /m at regex101.com
End With
Set colMatch = re.Execute(s)
For Each objMatch In colMatch
Debug.Print objMatch.SubMatches.Item(0)
Next
End Sub
关于正则表达式 VbScript 提前捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42153392/