java.util.regex.Matcher 混淆组 [英] java.util.regex.Matcher confused group

查看:60
本文介绍了java.util.regex.Matcher 混淆组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法获得正确的正则表达式匹配组.我的代码归结为以下内容:

I'm having trouble getting the right group of a regex match. My code boils down to following:

Pattern fileNamePattern = Pattern.compile("\\w+_\\w+_\\w+_(\\w+)_(\\d*_\\d*)\\.xml");
Matcher fileNameMatcher = fileNamePattern.matcher("test_test_test_test_20110101_0000.xml");

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

if (fileNameMatcher.matches()) {
    for (int i = 0; i < fileNameMatcher.groupCount(); ++i) {
        System.out.println(fileNameMatcher.group(i));
    }
}

我希望输出是:

2
test
20110101_0000

然而它:

2
test_test_test_test_20110101_0000.xml
test

有没有人解释一下?

推荐答案

Group(0) 是整个匹配,group(1), group(2), ... 是正则表达式匹配的子组.
为什么您希望测试"包含在您的组中?您没有定义一个组来匹配测试(您的正则表达式仅包含组 \d*_\d*).

Group(0) is the whole match, and group(1), group(2), ... are the sub-groups matched by the regular expression.
Why do you expect "test" to be contained in your groups? You didn't define a group to match test (your regex contains only the group \d*_\d*).

这篇关于java.util.regex.Matcher 混淆组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆