我想将以下正则表达式应用于字符串。它在 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);
\\b
是 word boundary ,这就是您想要的,而不是 "^"
和 "$"
指示开始于和结束于 分别
请注意,我的 capturing groups与你的不同。之前,您捕获的是 "@"
和 "[dot]"
等。现在“用户名”、“域”和“顶级域”正在被捕获,这就是我认为您想要的。
注意:您不需要转义 character classes 中的特殊字符,即[.]
代表句点,[\\.]
是不必要的。它仍然可以正常工作,因为您需要 \\\\
来实际匹配 \
,对此进行了解释 here .
关于java - 正则表达式不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19732242/