user1251683
user1251683

Reputation: 19

Regular Expression for paired brackets

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:

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

Upvotes: 2

Views: 2430

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336258

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

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.

Upvotes: 4

Mark Hurd
Mark Hurd

Reputation: 10931

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.

Upvotes: 2

Related Questions