java - 无法使用正则表达式匹配字符串 "help"中的字符串 "[help]"

标签 java regex

我无法使其正确匹配。它只打印“[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/

相关文章:

java - SpringBoot + RabbitMQ 抛出错误 : java.net.ConnectException: Connection refused

java - 在 Android-Java 中操作 html 响应

java - 正则表达式java中方括号外的Charat运算符

python - Python 正则表达式 findall 的一些问题

java - 使用元素路径查找 xml 中具有 namespace 的元素

java - android KITKAT 和旧版本的问题

java - ImageJ java API : how to test if command exists?

java - 如何找到所有特殊字符并将其打印在给定字符串中?

regex - 来自正则表达式的虚拟机

Java String.contains() 处理自然数