java - 正则表达式不起作用

标签 java regex

我想将以下正则表达式应用于字符串。它在 Grant Skinners Regexr 上运行良好,在 http://www.regexplanet.com/advanced/java/index.html 上也运行良好。 (区分大小写的设置)但 Java 不会吞掉它。它从来没有击中 while 循环。这是我的代码:

public static void main(String args[]) {
   final String testString =
      "lorem upsadsad asda 12esadas <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e7a6b7d7a4e7a6b7d7a206d6163" rel="noreferrer noopener nofollow">[email protected]</a> asdlawaljkads test[at]test" +
      "[dot]com test jasdsa meter";
   final Pattern ptr =
      Pattern.compile(
         "^[A-Z0-9\\._%+-]+(@|\\s*\\[\\s*at\\s*\\]\\s*)[A-Z0-9\\.-]+" +
         "(\\.|\\s*\\[\\s*dot\\s*\\]\\s*)[a-z]{2,6}$",
         Pattern.CASE_INSENSITIVE);

    try {
        final Matcher mat = ptr.matcher(testString);
        while (mat.find()) {
            final String group1 = mat.group(1);
            System.out.println(group1);
            final String group2 = mat.group(2);
            System.out.println(group2);
            final String group3 = mat.group(3);
            System.out.println(group3);
        }
    } catch (final Exception e) {
        e.printStackTrace();
    }
}

最佳答案

不需要复杂的正则表达式。正如另一位用户建议的,将 "[dot]" 替换为 ".",将 "[at]" 替换为 "@",即:

myAddressLine = myAddressLine.replace("[dot]", ".").replace("[at]","@");

现在,我们可以将您的正则表达式简化为:

Pattern.compile(
"\\b([a-z0-9._%+-]+)@([a-z0-9.-]+)\\.([a-z]{2,6})\\b", Pattern.CASE_INSENSITIVE);

\\bword boundary ,这就是您想要的,而不是 "^""$" 指示开始于结束于 分别

请注意,我的 capturing groups与你的不同。之前,您捕获的是 "@""[dot]" 等。现在“用户名”、“域”和“顶级域”正在被捕获,这就是我认为您想要的。

注意:您不需要转义 character classes 中的特殊字符,即[.]代表句点,[\\.]是不必要的。它仍然可以正常工作,因为您需要 \\\\ 来实际匹配 \,对此进行了解释 here .

关于java - 正则表达式不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19732242/

相关文章:

java - Spring 容器如何引用我们作为参数传递给方法的接口(interface)或类类型

java - 如何从 .vm 文件的 javascript 调用 java 方法

python - 使用 lookhead/lookaround 查找句子中的所有数字

python - 如何使用正则表达式只替换括号内的内容?

regex - Nginx request_uri没有参数

java - 动态加载spring xml配置

java - HashMap/Hashtable 在 for 循环中不返回 int 作为键值

java - 创建正则表达式匹配数组

javascript - 在逗号分隔列表上应用 url 验证正则表达式

regex - "(?x::"在Boost regex替换中是什么意思,其中 "x"是数字吗?