我有一个非常宽松的正则表达式来匹配字符串中的任何类型的url:[a-z]+[:.].*?(?=\s|$)
唯一的问题是,此正则表达式也将匹配电子邮件的域,而我想从匹配项中排除任何电子邮件地址。
确切地说,我确实想要以下匹配项(匹配的字符串以粗体显示)
测试example.com测试
我尝试过的任何解决方案都排除emailstring
和匹配myemail.com
这是一个更完整的测试用例https://regex101.com/r/NsxzCM/3/
这是一个两步建议,将正则表达式replace
与lambda结合使用。第一个正则表达式查找看起来像普通URL或电子邮件的所有内容,然后第二个正则表达式过滤出看起来像电子邮件地址的字符串:
input =
"test\n" +
"example.com\n" +
"www.example.com\n" +
"test sub.example.com test\n" +
"http://example.com\n" +
"test http://www.example.com test\n" +
"http://sub.example.com\n" +
"https://example.com\n" +
"https://www.example.com\n" +
"https://sub.example.com\n" +
"\n" +
"test [email protected] <- i don't want to match this\n" +
"[email protected] <- i don't want to match this\n" +
"\n" +
"git://github.com/user/project-name.git\n" +
"irc://irc.undernet.org:6667/mIRC jhasbdjkbasd\n";
includeRegex = /(?:[\w/:@-]+\.[\w/:@.-]*)+(?=\s|$)/g ;
excludeRegex = /.*@.*/ ;
result = input.replace(includeRegex, function(s) {
if (excludeRegex.test(s)) {
return s; // leave as-is
} else {
return "(that's a non-email url: " + s +")";
}
});
console.log(result);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句