1

我无法让它正确匹配。它只打印“[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));
        }
4

1 回答 1

4

您需要检查<=groupCount。像这样:

for (int i = 0; i <= m.groupCount(); i++) {

来自Matcher Javadoc

任何小于或等于此方法返回值的非负整数都保证是此匹配器的有效组索引。

于 2013-01-18T00:05:17.500 回答