我有一个非常松散的正则表达式来匹配字符串中的任何类型的url:[a-z]+[:.].*?(?=\s|$)唯一的问题是,这个regex也将匹配电子邮件的域,而不是我想从匹配中排除任何电子邮件地址。
准确地说,我希望下面的匹配(匹配的字符串以粗体表示)
example.com试验 测试emailstring@myemail.com
我尝试过的任何解决方案都不包括emailstring并与myemail.com匹配。
下面是一个更完整的测试用例https://regex101.com/r/NsxzCM/3/
发布于 2018-05-30 12:53:34
这里有一个两步的建议,使用regex replace和lambdas。第一个regex查找所有看起来像普通URL或电子邮件的内容,第二个regex则过滤出看起来像电子邮件地址的字符串:
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 example@example.com <- i don't want to match this\n" +
"example@example.co.uk <- 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);
发布于 2020-12-30 21:08:57
(:^|[^@\.\w-])([-\w:.]{1,256}\.[\w()]{1,6}\b)有帮助,但我不知道为什么它也匹配额外的\
发布于 2021-10-19 11:54:30
我想你需要这样的东西:
const URL_INCLUDE_REGEX = /[(http(s)?):\/\/(www\.)?a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/ig;
const URL_EXCLUDE_REGEX = /.*@.*/;第二种是排除电子邮件。最后的代码是:
const text = "My website is example.com";
// const text = "My email is test@example.com"; <- this will not be matched as there is email, not a url
let result = false;
text.replace(URL_INCLUDE_REGEX, (matchedText) => {
if(!URL_EXCLUDE_REGEX.test(matchedText)) {
result = true;
}
});
return result;结果将是true或false
https://stackoverflow.com/questions/50604549
复制相似问题