gpt4 book ai didi

java - JAVA 的正则表达式获取可选组

转载 作者:行者123 更新时间:2023-12-02 13:07:28 26 4
gpt4 key购买 nike

我尝试将用量中的非英文文本匹配到name=用量以及将用量2匹配到name=用量number=2。我在 RegexPlanet 上尝试了 (\p{L}+)(\d*) ,它可以工作,但是当它在 java 中运行时,无法将 2 取出第二个测试用例。

代码如下:

String pt = "(?<name>\\p{L}+)(?<number>\\d*)";
Matcher m = Pattern.compile(pt).matcher(t.trim());
m.find();
System.out.println("Using [" + pt + "] vs [" + t + "] GC=>" +
m.groupCount());
NameID n = new NameID();
n.name = m.group(1);

if (m.groupCount() > 2) {
try {
String ind = m.group(2);
n.id = Integer.parseInt(ind);
} catch (Exception e) { }
}

最佳答案

String t = "用量2";
String pt = "^(?<name>\\p{L}+)(?<number>\\d*)$";
Matcher m = Pattern.compile(pt).matcher(t.trim());
if (m.matches()) {
String name = m.group("name");
Integer id = m.group("number").length() > 0 ? Integer.parseInt(m.group("number")) : null;
System.out.println("name=" + name + ", id=" + id); // name=用量, id=2
}

您的正则表达式工作正常,但您的 Java 代码有一些问题。请参阅 javadoc 以了解 groupCount():

Group zero denotes the entire pattern by convention. It is not included in this count.

关于java - JAVA 的正则表达式获取可选组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44082453/

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