Java Regex:匹配带有多组括号的字符串

时间:2012-04-12 21:23:03

标签: java regex

我试图弄清楚如何编写一个正则表达式,它将匹配包含任意数量非括号字符的4组括号。

例如,这些应该匹配。

[hello][world][foo][bar]
[][][][]

这些不应该:

[a][b][c]
[a][b][c][d]e
[[a]][b][c][d]

如果我没有弄错的话,这(下面)似乎与一组括号和其中的字符相匹配。

\\[[^\\[\\]]*\\]

我认为我可以通过执行以下操作将其扩展到4套,但它无效。

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

我在这里缺少什么?在此先感谢您的帮助。我很感激。

2 个答案:

答案 0 :(得分:8)

试试这个:

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

为你打破这个:

"^(\\[[^\\[\\]]*\\]){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.

答案 1 :(得分:4)

您需要对要重复的块进行分组,否则它只匹配重复最后] 4次的内容:

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

正如詹姆斯在下面指出的那样,您似乎尝试使用[]进行分组,而不是()。这可能是您的错误发生的地方。