user5616998
user5616998

Reputation: 49

Regex for JAVA to get optional group

I try to match non english text from 用量 to name=用量 and 用量2 to name=用量 and number=2. I tried (\p{L}+)(\d*) on RegexPlanet, it works, but when get it run in java, can not get the 2 out the second test case.

Here's the code:

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) { }
}

Upvotes: 0

Views: 1174

Answers (1)

steffen
steffen

Reputation: 16948

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
}

Your regex works fine, but your Java code has some issues. See javadoc for groupCount():

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

Upvotes: 2

Related Questions