简体   繁体   English

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

[英]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. 我试图弄清楚如何编写一个正则表达式,该表达式将匹配包含任意数量的非括号字符的4组括号。

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套,但它不起作用。

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

What am I missing here? 我在这里错过了什么? Thanks in advance for any help. 在此先感谢您的帮助。 I appreciate it. 我很感激。

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.

You need to group the chunk that you want to repeat, otherwise it will only match something that repeats the final ] 4 times: 你需要组要重复块,否则只会匹配的东西,重复最后] 4次:

(\\[[^\\[\\]]*\\]){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. 这可能是您的错误出现的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM