2

有没有办法使用正则表达式拆分 Java 字符串并返回一个反向引用数组?

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

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
4

1 回答 1

5

是的,使用pacakge中的PatternandMatcher类。java.util.regex

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));
    }
}
于 2012-11-18T04:28:58.560 回答