简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM