Regular Expression for paired brackets

北慕城南 提交于 2020-01-15 05:50:09

问题


The Input Line goes like this (just a part of it):

[[Text Text Text]][[text text text]]asdasdasdasda[[asdasdasdasd]]

What I want is to list all matches wherein text enclosed in a pair of [[ and ]]. I did try several patterns, but all fails when a unclosed [[ or ]] is within the input line. For example:

[[text[[text text TEXT text]]

Also, what if a single bracket exist within the input line, like:

[[text [text] text TEXT text]]

The regex pattern I used was:

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

回答1:


\[\[(?:(?!\[\[|\]\]).)*\]\]

matches [[<anything>]], where <anything> may not contain double brackets but everything else. You might need to set the DOTALL option of your regex engine to allow the dot to match newlines.

It will match [[match [this] text]] in

[[don't match this [[match [this] text]] don't match this]]

Explanation:

\[\[     # Match [[
(?:      # Match...
 (?!     #  (unless we're right at the start of
  \[\[   #   [[
 |       #  or
  \]\]   #   ]]
 )       #  )
 .       # ...any character
)*       # Repeat any number of times
\]\]     # Match ]]

Caveat: It will match [[match [this]] in the text [[match[this]]] because regexes can't count.




回答2:


What to do with unclosed or single brackets is up to your specification. Until then

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

works for me (where the whole of the two problematic strings are matched.



来源:https://stackoverflow.com/questions/9580319/regular-expression-for-paired-brackets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!