问题
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