首页 > 解决方案 > URL/字符串的正则表达式 - 如果协议返回 false

问题描述

尝试创建一个字符串不应以 http(s)://、http(s)://www 开头的正则表达式。字符串的其余部分可以是任何东西。

我使用了这个 regeg,但如果我们有,它会返回 truehttp://

^(http://www.|https://www.|http://|https://)?[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(:[0-9]{1,5})?(/.*)?$

我试过的另一个是

var re = new RegExp("(http|https|ftp)://");
var str = "http://xxxx.com";
var match = re.test(str);
console.log(match);

这一个也回归真实。

演示在这里

let re = /(http|https|ftp):///;
let url = 'xxxx.xxxx.xxxx'; // this is valid but test returns false
let url2 = 'https://www.xxzx.com/xxx.aspx'; // this should fail as there is https://www in url

console.log(re.test(url)); //
console.log(re.test(url2)); //

这可以用正则表达式吗?

标签: javascriptregexregex-lookaroundsregex-groupregex-greedy

解决方案


您需要在正则表达式中使用负前瞻来丢弃以httpor httpsor等​​协议开头的字符串ftp。你可以使用这个正则表达式,

^(?!(?:ftp|https?):\/\/(www\.)?).+$

正则表达式演示

JS 演示,

const arr = ['xxxx.xxxx.xxxx','ftp://www.xxzx.com/xxx.aspx','https://www.xxzx.com/xxx.aspx','http://xxxx.com','https://xxzx.com/xxx.aspx','http://www.xxxx.com']

arr.forEach(s => console.log(s + " --> " + /^(?!(?:ftp|https?):\/\/(www\.)?).+$/.test(s)))


推荐阅读