首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正则表达式-匹配[ and ]之间的任意倍数

正则表达式-匹配[ and ]之间的任意倍数
EN

Stack Overflow用户
提问于 2012-09-10 21:42:42
回答 5查看 240关注 0票数 3

我需要使用正则表达式匹配[[ and ]]之间的任何内容。然后我需要将在括号之间找到的所有值放入一个数组中。

示例文本:

代码语言:javascript
复制
here is some 'test text [[[media-2 large right]]], [[[image-0 large left]]] the another token [[[image-1]]

从上面的文本中,我需要匹配前两个:

代码语言:javascript
复制
1, [[[media-2 large right]]]
2, [[[image-0 large left]]]

但不是最后一个,因为它最后只有两个[。

EN

回答 5

Stack Overflow用户

发布于 2012-09-10 21:57:30

这将检查以下内容:

  1. [[[
  2. Followed by:
    1. Anything ]

-or-

  • One to two ] not that that or-

  • One to two]not that

后跟]]]的是

代码语言:javascript
复制
preg_match_all('/\[\[\[(?:(?:[^\]]*|]{1,2}(?!]))*)]]]/', $string, $matches);
print_r($matches[0]);

这种正则表达式的好处是可以在三方括号包装器(例如[[[foo]bar]]] )中匹配]

注意: ]不需要进行转义,但在字符类内部除外。

票数 2
EN

Stack Overflow用户

发布于 2012-09-10 22:26:34

一般的解决方案是这样的:

代码语言:javascript
复制
\[{3}(?=.*?\]{3}(?!\]))((?:(?!\]{3}(?!\])).)*)

上面写着

代码语言:javascript
复制
\[{3}         # 3 opening square brackets
(?=           # begin positive look-ahead ("followed by..."
  .*?\]{3}    #   ...3 closing brackets, anywhere ahead (*see explanation below)
  (?!\])      #   negative look-ahead: no more ] after the 3rd one
)             # end positive look-ahead
(             # begin group 1
  (?:         #   begin non-matching group (for atomic grouping)
    (?!       #     begin negative look-ahead ("not followed by"):
      \]{3}   #       ...3 closing square brackets
      (?!\])  #       negative look-ahead: no more ] after the 3rd one
    )         #     end negative look-ahead
    .         #     the next character is valid, match it
  )           #   end non-matching group
)             # end group 1 (will contain the wanted substring)

当长输入字符串中没有"]]]"时,积极的先行检查是一个安全的子句,允许表达式快速失败。

一旦确定"]]]"将在字符串前面的某个点跟随,负前视确保表达式正确匹配字符串,如下所示:

代码语言:javascript
复制
[[[foo [some text] bar]]]
                 ^
                 +-------- most of the other solutions would stop at this point

该表达式检查每个字符是否跟有三个],因此在本例中它将包括" bar"

表达式的"no more ] after the 3rd one"部分确保匹配不会过早结束,因此在本例中:

代码语言:javascript
复制
[[[foo [some text]]]]

匹配结果仍然是"foo [some text]"

如果没有它,表达式将过早停止("foo bar [some text")。

副作用是我们实际上不需要匹配"]]]",因为积极的前瞻清楚地表明它们就在那里。我们只需要匹配它们,这是消极的前瞻做得很好。

请注意,如果您的输入包含换行符,则需要在"dotall“模式下运行表达式。

另请参阅:http://rubular.com/r/QFo9jHEh9d

票数 2
EN

Stack Overflow用户

发布于 2012-09-10 21:46:46

更安全的解决方案:

代码语言:javascript
复制
\[{3}[^\]]+?\]{3}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12352977

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档