0

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

<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*="-\/]*\]\]
4

3 回答 3

1

使用否定字符类怎么样

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

此类将匹配除“]”之外的任何内容

Regexr上查看

为避免方括号成为结果的一部分,您可以使用捕获组

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

并从第 1 组得到结果

或使用环视断言(如果您的正则表达式引擎支持它)

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

Regexr上查看

于 2013-12-16T10:40:49.253 回答
1

如果您可以使用前瞻:

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

意义:

\[\[    # 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

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

\[\[(.*?)\]\]
于 2013-12-16T10:41:13.287 回答
0

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

"\\[\\[\\(.*\\)\\]\\]"
于 2013-12-16T10:42:47.920 回答