简体   繁体   中英

Java: Regular expression doesn't work as expected

I have the following piece of code:

String range = "(15-42)";
String regexp = "(\\d{1,})(\\d{1,})";

Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(range);

m.find();

System.out.println(m.groupCount());

for(int i=0; i<=m.groupCount(); i++){
System.out.println("value:" + m.group());
}

And then I have the following output:

2
value: 15
value: 1
value: 5

But I'm only expecting to see 2 values: 15 and 42.

Why doesn't this work as expected?

The mistake is that you are always calling m.group() when you should be calling m.group(i) .

The other mistake is that you forgot the hyphen in your regex.

Working code:

String range = "(15-42)";
String regexp = "(\\d{1,})-(\\d{1,})";

Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(range);
m.find();
for (int i = 0; i <= m.groupCount(); i++) {
    System.out.println("value:" + m.group(i));
}

This prints the expected:

value:15-42
value:15
value:42

You need to add hyphen to the regex and use .group(i) and start with index 1 (because m.group(0) is the whole match value that you do not need):

String range = "(15-42)";
String regexp = "(\\d{1,})-(\\d{1,})";
Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(range);
if (m.find()) {
    System.out.println(m.groupCount());
    for(int i=1; i<=m.groupCount(); i++){
        System.out.println("value:" + m.group(i));
    }
}

See IDEONE demo

Now, you will have

2               // This is the number of capturing groups
value:15        // This is the value of the first capturing group
value:42        // This is the value of the second capturing group

Its a different method but you can use this solution

    System.out.println(m.groupCount());
    String[] value = m.group().split("-");

    for(int i=0; i<value.length; i++){
    System.out.println("value:" + value[i]);
    }

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