有没有办法使用正则表达式分割 Java 字符串并返回反向引用数组?
举一个简单的例子,假设我想从一个简单的电子邮件地址(仅限字母)中提取用户名和提供商。
String pattern = "([a-z]+)@([a-z]+)\\.([a-z]{3})";
String email = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="314442544371545c50585d1f525e5c" rel="noreferrer noopener nofollow">[email protected]</a>";
String[] backrefs = backrefs(email,pattern);
System.out.println(backrefs[0]);
System.out.println(backrefs[1]);
System.out.println(backrefs[2]);
这应该输出
user
email
com
最佳答案
是的,使用 Pattern
和 Matcher
来自 java.util.regex
pacakge 的类。
String pattern = "([a-z]+)@([a-z]+)\\.([a-z]{3})";
String email = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="493c3a2c3b092c24282025672a2624" rel="noreferrer noopener nofollow">[email protected]</a>";
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));
}
}
关于Java - 数组中的正则表达式反向引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13437471/