What regex matches any text that is entirely between square brackets?

Viewed 121

So if I have these lines:

test 1
[test 2]
[test] 3
test [4]
[test][5]
[te]st[6]

I would like only the 2nd and 5th lines to be matched ([test 2], [test][5]).

I know that we can match what's inside a pair of square brackets with regex
\[.*?\]

But how do we deal with multiple pairs and how to tell it to not match the line if there's anything outside of the square brackets?

Thanks

1 Answers

You can use

^(?:\[[^][]*])+$
^(?:\[[^\]\[]*\])+$

See the regex demo. Details:

  • ^ - start of string
  • (?: - start of a non-capturing group (remove ?: if you do not care or if non-capturing groups are not supported):
    • \[ - a [ char
    • [^][]* - zero or more chars other than ] and [
    • ] - a ] char
  • )+ - one or more repetitions of the pattern sequence inside the group
  • $ - end of string.

NOTE: in some regex flavors you need to escape more [ / ] than in others, so to play safe, I added the fully escaped regex version.

Related