有没有办法使用正则表达式拆分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
答案 0 :(得分:5)
是的,使用java.util.regex
包中的Pattern
和Matcher
类。
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));
}
}