首页 > 解决方案 > 如何知道正则表达式的哪一部分匹配?

问题描述

正则表达式=(i.*d.*n.*t.*)|(p.*r.*o.*f.*)|(u.*s.*r.*) 要匹配的字符串=profile

现在正则表达式将与字符串匹配。但我想知道哪个部分匹配。

意思是,我想要 (p.*r.*o. f. ) 作为输出

我怎样才能在 Java 中做到这一点?

标签: javaregexstringregex-group

解决方案


您可以检查哪个组匹配:

Pattern p = Pattern.compile("(i.*d.*n.*t.*)|(p.*r.*o.*f.*)|(u.*s.*r.*)");
Matcher m = p.matcher("profile");
m.find();
for (int i = 1; i <= m.groupCount(); i++) {
    System.out.println(i + ": " + m.group(i));
}

将输出:

1: null
2: profile
3: null

因为第二行不为空,所以它(p.*r.*o.*f.*)与字符串匹配。


推荐阅读