gpt4 book ai didi

java - 在线程 "main"java.lang.IndexOutOfBoundsException : No group 1 中得到异常

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:45:38 25 4
gpt4 key购买 nike

我有一个这样的字符串

"abc:def"

我需要检查它是否匹配。如果是,我想应用正则表达式并检索它的第一部分 ("abc")。

这是我的尝试:

Pattern pattern = Pattern.compile(".*:.*");
String name = "abc:def"
Matcher matcher = pattern.matcher(name);

if (matcher.find()) {
String group = matcher.group(1);
System.out.println(group);
}

它给了我

Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 1

最佳答案

您需要添加一个 capturing group在你的正则表达式中。这是通过将要捕获的内容放在括号内来完成的:

Pattern pattern = Pattern.compile("(.*):.*"); // <-- parentheses here
String name = "abc:def";
Matcher matcher = pattern.matcher(name);

if (matcher.find()) {
String group = matcher.group(1);
System.out.println(group); // prints "abc"
}

关于java - 在线程 "main"java.lang.IndexOutOfBoundsException : No group 1 中得到异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34588289/

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