Regex brackets and brackets next to eachother

89 Views Asked by At

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?

1

There are 1 best solutions below

1
heemayl On BEST ANSWER

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