user259175
user259175

Reputation:

Java Regex: Matching a string with multiple sets of brackets

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.

Upvotes: 2

Views: 2790

Answers (2)

maerics
maerics

Reputation: 156384

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.

Upvotes: 8

VeeArr
VeeArr

Reputation: 6178

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.

Upvotes: 4

Related Questions