1

I am looking for a regex that will match string(s) between a consecutive [ and ] parenthesis. I have a regex that looks like this \[(.*?)\] and it matches stuff between [ ] which might have a ] between it.

Example: String: [ text [text1] ]

should return [text1], [ text [text1] ]
currently my regex would return [ text [text1]

I believe this must have something to do with the look ahead assertion however, not sure how to look ahead more than one character.

HamZa
  • 14,671
  • 11
  • 54
  • 75
noi.m
  • 3,070
  • 5
  • 34
  • 57
  • 3
    What regex engine are you using ? Most engines can't do what you want :) Say hello to [this **recursive pattern**](http://regex101.com/r/vY6fL7) in PCRE – HamZa Jan 30 '14 at 10:28

1 Answers1

0

The following Method returns your desired result:

> echo "[ text [text1] ]" | egrep -o '\[([[:alnum:]]+)\]'
> [text1]

Explanation: It only works with extended regex - hence the use of egrep. The parameter -o only returns matching patterns. Lastly the characterclass [:alnum:] which is looked for to appear once or more inside the brackets, contains a-z, A-Z, 0-9 and underlines. Therefore it won't accept ] or [.

If you need to match more characters (for example: spaces), you'll need to add more into the matching-Pattern inside the brackets - like so:

> echo "[ text [text1 text2] ]" | egrep -o '\[([[:alnum:] ]+)\]'
> [text1 text2]
Marlon
  • 148
  • 6
  • The desired results with `[ text [text1 text2] ]` is `[ text [text1 text2] ]` and `[text1 text2]`. – HamZa Jan 30 '14 at 12:45
  • Ah yeah - you're right. I missed that (and your comment to the question as well). Why didn't you propose your working solution as answer, instead of posting it as a comment? Especially since - as you correctly stated - there probably won't be a solution to this in 'normal' regex. – Marlon Jan 30 '14 at 13:19
  • Because I like to give [definitve](http://stackoverflow.com/a/21443230) [detailed](http://stackoverflow.com/a/21395083) answers. If the asker did provide the engine s?he's using, I could have posted a befitting answer based on that. Otherwise, say for example I provided a PCRE solution and then s?he mentions that s?he's using .NET then I would have to edit and re-write my whole answer which is a pain to be honest. – HamZa Jan 30 '14 at 14:01
  • 1
    Ok, thanks for clarifying this. I just wondered if there was some unwritten or written rule that I wasn't aware of (like "Don't post an answer befor you proposed it in form of a comment" or likewise). – Marlon Jan 30 '14 at 15:10
  • I am using java. I see from this link (http://en.wikipedia.org/wiki/Comparison_of_regular_expression_engines) that recursion is not supported. So i guess this would not work in java atleast. Thanks anyway for the answer. – noi.m Feb 02 '14 at 06:47