我无法使其正确匹配。它只打印“[help]”,但我希望它匹配括号内的字符。
想要:
[help]
help
代码:
Pattern p = Pattern.compile("\\[(\\w+)\\]");
Matcher m = p.matcher("[help]");
m.find();
for (int i=0;i<m.groupCount(); i++) {
System.out.println(m.group(i));
}
最佳答案
您需要检查 <=
对于 groupCount。像这样:
for (int i = 0; i <= m.groupCount(); i++) {
来自Matcher Javadoc :
Any non-negative integer smaller than or equal to the value returned by this method is guaranteed to be a valid group index for this matcher.
关于java - 无法使用正则表达式匹配字符串 "help"中的字符串 "[help]",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14390342/