Matt Eno
Matt Eno

Reputation: 696

Regular expression to match a regular expression inside square brackets

I have a string that contains a regular expression within square brackets, and can contain more than 1 item inside square brackets. below is an example of a string I'm using:

[REGEX:^([0-9])*$][REGEXERROR:That value is not valid]

In the example above, I'd like to match for the item [REGEX:^([0-9])*$], but I can't figure out how.

I thought I'd try using the regular expression \[REGEX:.*?\], but it matches [REGEX:^([0-9] (ie; it finishes when it finds the first ]).

I also tried \[REGEX:.*\], but it matches everything right to the end of the string.

Any ideas?

Upvotes: 1

Views: 906

Answers (1)

Herrington Darkholme
Herrington Darkholme

Reputation: 6315

Suppose you are using PCRE, this should be able to find nested brackets in regular expressions:

\[REGEX:[^\[]*(\[[^\]]*\][^\[]*)*\]

This technique is called unrolling. The basic idea of this regex is:

  1. match the starting brackets
  2. match all characters that are not brackets
  3. match one brackets
  4. match all trailing characters that are not brackets
  5. then repeat 3 and 4 until the last closing bracket comes

Explanation with free-space:

\[              # start brackets
   REGEX:       # plain match 
   [^\[]*       # match any symbols other than [
   (            # then match nested brackets  
     \[         # the start [ of nested
     [^\]]*     # anything inside the bracket
     \]         # closing bracket 
     [^\[]*     # trailing symbols after brackets
   )*           # repeatable  
\]              # end brackets

Reference: Mastering Regular Expression

Upvotes: 4

Related Questions