regex - 如何使用正则表达式一次捕获字符串的多个部分?
问题描述
我需要在一个较长的字符串中捕获几个字符串strText
并处理它们。我使用VBA。
strText
:
Salta pax {wenn([gender]|1|orum|2|argentum)} {[firstname]} {[lastname]},
ginhox seperatum de gloria desde quativo,
dolus {[start]} tofi {[end]}, ([{n_night]}
{wenn([n_night]|1|dignus|*|digni)}), cum {[n_person]}
{wenn([n_person]|1|felix|*|semporum)}.
Quod similis beruntur: {[number]}
我试图strText
在花括号内捕获 的不同部分:
- 如果方括号内只有一个字符串,我想捕获该字符串:
{[firstname]}
-->firstname
- 如果有条件操作(以 开头
wenn()
),我想捕获方括号内的字符串以及后面的数字值对:
{[gender]|1|orum|2|argentum}
-- > gender
//1=orum
2=argentum
我设法定义了一种模式来完成上述任何一项任务,
例如\{\[(.+?)\]\}
捕获方括号内的字符串,
请参阅此 regex101
但我认为必须有一种方法可以实现上述所有功能?
解决方案
我不确定以下代码是否对您有帮助。它使用|
符号来捕获这两种情况。
Function extractStrings(strText As String) As MatchCollection
Dim regEx As New RegExp
Dim SubStrings As MatchCollection
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = "(\{\[)(.+?)(\]\})|(wenn\(\[)(.+?)(\])(\|)(.+?)(\|)(.+?)(\|)(.+?)(\|)(.+?)(\)\})"
End With
On Error Resume Next
Set extractStrings = regEx.Execute(strText)
If Err = 0 Then Exit Function
Set extractStrings = Nothing
End Function
Sub test()
Dim strText As String
strText = "Salta pax {wenn([gender]|1|orum|2|argentum)} {[firstname]} {[lastname]},ginhox seperatum de gloria desde quativo,dolus {[start]} tofi {[end]}, ([{n_night]} " & _
"{wenn([n_night]|1|dignus|*|digni)}), cum {[n_person]}{wenn([n_person]|1|felix|*|semporum)}.Quod similis beruntur: {[number]}"
Dim SubStrings As MatchCollection
Dim SubString As Match
Set SubStrings = extractStrings(strText)
For Each SubString In SubStrings
On Error Resume Next
If SubString.SubMatches(1) <> "" Then
Debug.Print SubString.SubMatches(1)
Else
Debug.Print "wenn(" & SubString.SubMatches(4) & "|" & SubString.SubMatches(7) & "=" & SubString.SubMatches(9) & "|" & SubString.SubMatches(11) & "=" & SubString.SubMatches(13) & ")"
End If
Next SubString
End Sub
您可以使用循环遍历所有子字符串for each
。我很清楚,正则表达式模式不是最优的,但至少它可以解决问题。
推荐阅读
- sql - 查询/设计性能问题:如何以最有效的方式通过“链接”表获取 Id?
- php - 如何修复 Cloud Firestore 返回空数组?
- python - 扩展 Django 用户模型并在管理员上显示
- docker - 通过容器的构建映像拒绝 Docker 权限
- python - Python 中的本地和全局列表
- c++ - 我刚开始使用 C++,想编写一个计算器,但我的逻辑在某个地方是错误的
- ruby-on-rails - 不显示文本框和格式化工具
- angular - 刷新页面时无法激活已激活的插座
- google-chrome - 如何使用 Jenkins 和 Katalon Studio 实现真正的浏览器测试(启动浏览器)?
- python - Jupyter:如何更改 SelectMultiple() 等小部件的颜色?