首页 > 解决方案 > 如何使用正则表达式一次捕获字符串的多个部分?

问题描述

我需要在一个较长的字符串中捕获几个字符串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在花括号内捕获 的不同部分:

  1. 如果方括号内只有一个字符串,我想捕获该字符串:

{[firstname]}-->firstname

  1. 如果有条件操作(以 开头wenn()),我想捕获方括号内的字符串以及后面的数字值对:

{[gender]|1|orum|2|argentum}-- > gender//1=orum2=argentum

我设法定义了一种模式来完成上述任何一项任务,

例如\{\[(.+?)\]\}捕获方括号内的字符串,
请参阅此 regex101

但我认为必须有一种方法可以实现上述所有功能?

标签: regexvba

解决方案


我不确定以下代码是否对您有帮助。它使用|符号来捕获这两种情况。

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。我很清楚,正则表达式模式不是最优的,但至少它可以解决问题。


推荐阅读