【问题标题】:leading space with regex match正则表达式匹配的前导空格
【发布时间】:2014-12-09 05:03:47
【问题描述】:

正则表达式的新手,我正在尝试跳过第一组括号[word1],并匹配用左括号和右括号[...} 括起来的任何剩余文本

文字:[word1] This is a [word2]bk{not2} sentence [word3]bk{not3}

模式:[^\]]\[.*?\}

所以我想要匹配 [word2]bk{not2}[word3]bk{not3},它确实有效,但我最终在每场比赛中都有一个前导空格。玩了几天(并且做了很多阅读),但我显然仍然错过了一些东西。

【问题讨论】:

    标签: regex vba


    【解决方案1】:
    \[[^} ]*}
    

    试试这个。查看演示。

    https://regex101.com/r/qJ8qW5/1

    【讨论】:

    • 谢谢,这行得通,现在我只需要找出原因。仍处于学习曲线的陡峭部分。
    【解决方案2】:

    [^]] 在您的模式匹配前导空格中。匹配任何没有] 的字符。

    例如,当文本为[word1] This is a X[word2]bk{not2}时, 模式[^\]]\[.*?\} 匹配X[word2]bk{not2}

    如果[wordN}{notN} 之间没有出现任何左括号,您可以使用:

    \[[^\[}]*}

    或者,您也可以将Submatches 与捕获组一起使用。

    Sub test()
        Dim objRE As Object
        Dim objMatch As Variant
        Dim objMatches As Object
    
        Dim strTest As String
    
        strTest = "[word1] This is a [word2]bk{not2} sentence [word3]bk{not3}"
        Set objRE = CreateObject("VBScript.RegExp")
    
        With objRE
            .Pattern = "[^\]](\[.*?\})"
            .Global = True
        End With
    
        Set objMatches = objRE.Execute(strTest)
        For Each objMatch In objMatches
            Debug.Print objMatch.Submatches(0)
        Next
    
        Set objMatch = Nothing
        Set objMatches = Nothing
        Set objRE = Nothing
    End Sub
    

    在此示例代码中,模式具有用于分组的括号。

    【讨论】:

    • 感谢您的解释和代码,您的解决方案也有效(仍在尝试找出原因)。对不起,我只能接受一个答案,但我做了“有用”的指标。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 2010-10-08
    相关资源
    最近更新 更多