简体   繁体   English

Java:正则表达式不能按预期工作

[英]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.但我只希望看到 2 个值:15 和 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) .该错误是,你总是调用m.group()时,你应该调用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):您需要在正则表达式中添加连字符并使用.group(i)并从索引1开始(因为m.group(0)是您不需要的整个匹配值):

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 demoIDEONE 演示

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]);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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