Java - 数组中的Regex反向引用

时间:2012-11-18 04:23:49

标签: java regex backreference

有没有办法使用正则表达式拆分Java String并返回反向引用数组?

举个简单的例子,假设我想提取用户名&来自简单电子邮件地址的提供者(仅限字母)。

String pattern = "([a-z]+)@([a-z]+)\\.([a-z]{3})";
String email = "user@email.com";

String[] backrefs = backrefs(email,pattern);

System.out.println(backrefs[0]);
System.out.println(backrefs[1]);
System.out.println(backrefs[2]);

这应输出

user
email
com

1 个答案:

答案 0 :(得分:5)

是的,使用java.util.regex包中的PatternMatcher类。

String pattern = "([a-z]+)@([a-z]+)\\.([a-z]{3})";
String email = "user@email.com";
Matcher matcher = Pattern.compile(pattern).matcher(email);
// Check if there is a match, and then print the groups.
if (matcher.matches())
{
    // group(0) contains the entire string that matched the pattern.
    for (int i = 1; i <= matcher.groupCount(); i++)
    {
        System.out.println(matcher.group(i));
    }
}