Java - 数组中的正则表达式反向引用

标签 java regex backreference

有没有办法使用正则表达式分割 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

最佳答案

是的,使用 PatternMatcher来自 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/

相关文章:

java - 如何将 OO Perl 转换为 Java?

c++ - 从 XML 中提取特定数字属性的有效方法

Python:并行编译正则表达式

python : pass regex back-reference value to method

java - 测试复杂的数据场景

java - 使用 JPA 执行查询时出错

java - 如何使用 Netbeans 自动更改 Jtextfield 中的字符

java - String.matches() 引发 PatternSyntaxException?

regex - regexp_replace 中的 psql 大写反向引用字符串

php - 如何在递归正则表达式中进行反向引用匹配?