gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:38:17 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com