0

I'm a regex novice and I cannot figure out how to match the following:

String example:

"This is my string [something: something] and the string is very pretty [something: something][a][b][c]."

At the moment I got a regex that matches all start and end square brackets. \[([^]]*)\].

This yields the following

  • [something: something]
  • [something: something]
  • [a]
  • [b]
  • [c]

I want to group standalone brackets and brackets which has brackets next to it.

The regex should group it like;

  • [something: something]
  • [something: something][a][b][c]

Anyone able to help?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

1 Answers1

2

You can do:

((?:\[[^]]*\])+)
  • The non-captured group (?:\[[^]]*\]) matches [, then any number of characters upto ] and then ]

  • The captured group ((?:\[[^]]*\])+) matches one or more occurrence of the non-captured group

Demo

heemayl
  • 39,294
  • 7
  • 70
  • 76
  • Nice. I was thinking about doing lookaheads to not match a closing ] if it had a following [ and things like that. This is a much simpler solution than mine would have been. :) – Chris Jun 08 '16 at 10:23