【问题标题】:Match the content of double square brackets匹配双方括号的内容
【发布时间】:2013-12-16 10:35:37
【问题描述】:

我有一个字符串,我想匹配双方括号的内容: 示例:

<p><span>"Sed ut perspiciatis vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</span></p><p><span>[[image file="2013-12/5s_1.jpg" alt="IPhone 5s" title="IPhone 5s" ]]</span></p><p><span>[[download file="2013-12/modulo-per-restituzione-prodotti-.pdf" icon="icon" text="" title="Download" ]]</span></p>

结果:

download file="2013-12/module-res.pdf" icon="icon" text="" title="Download" 

image file="2013-12/5s_1.jpg" alt="IPhone 5s" title="IPhone 5s" 

考虑到这两个字符串可以包含任何类型的字符,我尝试了这个解决方案,但我遇到了其他字符的问题:

\[\[[\w+\s*="-\/]*\]\]

【问题讨论】:

    标签: regex square-bracket


    【解决方案1】:

    如何使用negated character class

    \[\[[^\]]*\]\]
    

    这个类可以匹配除“]”之外的任何东西

    Regexr这里查看

    为避免方括号成为结果的一部分,您可以使用capturing group

    \[\[([^\]]*)\]\]
    

    并从第 1 组中获取结果

    或使用lookaround assertions(如果您的正则表达式引擎支持)

    (?<=\[\[)[^\]]*(?=\]\])
    

    Regexr查看它

    【讨论】:

    • 好的,这非常适合我的范围。谢谢@stema,您的不带括号的解决方案非常有用。
    【解决方案2】:

    如果你可以使用前瞻:

    \[\[(([^]]|[]](?!\]))*)\]\]
    

    意思:

    \[\[    # match 2 literal square brackets
     (      # match
        [^]]         # a non-square bracket
        |            # or
        []](?!\])    # a square bracket not followed by a square bracket
     )*     # any number of times
    \]\]    # match 2 literal right square brackets
    

    或者你可以使用惰性量词:

    \[\[(.*?)\]\]
    

    【讨论】:

    • 谢谢,这也可以是我的解决方案,很好地解释了@perreal。
    【解决方案3】:

    此正则表达式将选择方括号,但使用 group(1) 您将只能获取内容:

    "\\[\\[\\(.*\\)\\]\\]"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-25
      相关资源
      最近更新 更多