gpt4 book ai didi

javascript - URL/字符串的正则表达式 - 如果协议(protocol)返回 false

转载 作者:行者123 更新时间:2023-11-30 09:14:32 25 4
gpt4 key购买 nike

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

我使用了这个 regeg 但如果我们有 http://

它会返回 true
^(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);

这个也返回 true。

此处演示

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)); //

这可以用正则表达式实现吗?

最佳答案

您需要在正则表达式中使用否定前瞻来丢弃以 httphttpsftp 等协议(protocol)开头的字符串。你可以使用这个正则表达式,

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

Regex Demo

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)))

关于javascript - URL/字符串的正则表达式 - 如果协议(protocol)返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56070842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com