Regular expression for pair brackets

The input line looks like this (only part of it):

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

I want the list of all matches to contain text enclosed in a couple [[ and ]] . I tried several templates, but everything fails when the private [[ or ]] is inside the input line. For example:

 [[text[[text text TEXT text]] 

Also, what if there is one bracket in the input line, for example:

 [[text [text] text TEXT text]] 

I used the regex pattern:

 \[\[[^\[\[]*\]\] 
+2
regex regex-negation
source share
2 answers
 \[\[(?:(?!\[\[|\]\]).)*\]\] 

matches [[<anything>]] , where <anything> may not contain double brackets, but everything else. You may need to set the DOTALL parameter of your regular expression engine so that the dot matches the newline characters.

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 ]] 

Caution: it will match [[match [this]] in the text [[match[this]]] , because regular expressions cannot be counted.

+3
source share

What to do with open or single brackets depends on your specifications. Until

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

works for me (where all two problem lines are matched.

+2
source share

All Articles