gpt4 book ai didi

java - 从正则表达式中提取子字符串

转载 作者:行者123 更新时间:2023-11-30 06:53:32 26 4
gpt4 key购买 nike

我有一个输入字符串,在 java 中应如下所示:
String input = add entity <a-zA-Z>,<a-zA-z>
现在我想检查给定的字符串是否具有正确的格式。如果是这样,我想得到手上的话。

我已经有了检查部分

boolean foo(String input) {
Pattern pattern = Pattern.compile("add entity [a-zA-Z]*[,][a-zA-Z]*");
Matcher matcher = pattern.matcher(input);
return matcher.matches();
}

我在这里发现了其他几个问题,他们已经解决了类似的问题

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

但是如果我这样做,控制台总是会抛出异常:

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

有人可以建议我如何解决这个问题吗?非常感谢你们。

最佳答案

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

此错误是由于您的正则表达式模式没有捕获组 #1 造成的。

您可以将模式更改为:

Pattern pattern = Pattern.compile("add entity ([a-zA-Z]*,[a-zA-Z]*)");

这样“添加实体”的部分就被捕获在组#1中。请注意,无需在正则表达式模式中转义逗号。

关于java - 从正则表达式中提取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42258815/

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