2

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.

2 Answers 2

8

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the detailed reply. I'm confused as to when one uses brackets or parentheses. "[^\\[\\]]*" = zero or more non-bracket characters, but "(abc){4}" = abc four times. When is one supposed to be used versus the other?
@Dazarath: the repetition/quantifier operators (?, +, *, {n,m}) act on the previous token, and capturing groups (...) and character classes [...] both happen to be tokens. In fact, it is common to use a capturing group (or non-capturing group (?:...)) precisely because it creates a token out of a sequence. So if you want to match the word "foo" any number of times you can't say foo* because the previous token is o, so you need to say (foo)*.
4

You need to group the chunk that you want to repeat, otherwise it will only match something that repeats the final ] 4 times:

(\\[[^\\[\\]]*\\]){4}

As James points out below, it looks like you were trying to use [] for grouping, instead of (). This is likely where your error arose.

2 Comments

You actually need to drop those extra outer brackets.
Whoops, copy/paste failure. Fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.