Java Regex: Matching a string with multiple sets of brackets

java, regex

Solution

Try this:

Pattern p = Pattern.compile("^(\\[[^\\[\\]]*\\]){4}$");

To break that down for you:

"^(\\[[^\\[\\]]*\\]){4}$"
 ││├─┘├───────┘│├─┘ │  └─ the end of the line.
 │││  │        ││   └─ repeat the capturing group four times.
 │││  │        │└─ a literal "]"
 │││  │        └─ the previous character class zero or more times.
 │││  └─ a character class containing anything but the literals "[" and "]"
 ││└─ a literal "[".
 │└─ start a capturing group.
 └─ the beginning of the string.

Problem

I am trying to figure out how to write a regex expression that would match 4 sets of brackets containing any number of non-bracket characters. For example, these should be matched. ``` [hello][world][foo][bar] [][][][] ``` These should not: ``` [a][b][c] [a][b][c][d]e [[a]][b][c][d] ``` If I'm not mistaken, this (below) seems to match one set of brackets and the characters within. ``` \\[[^\\[\\]]*\\] ``` I thought that I could extend it to 4 sets by doing the following, but it's not working. ``` [\\[[^\\[\\]]*\\]]{4} ``` What am I missing here? Thanks in advance for any help. I appreciate it.

Original source