【发布时间】:2019-09-27 23:08:22
【问题描述】:
尝试创建一个字符串不应以 http(s)://、http(s)://www 开头的正则表达式。字符串的其余部分可以是任何东西。
我使用了这个正则表达式,但如果我们有 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)); //
这可以用正则表达式吗?
【问题讨论】:
-
你认为你的正则表达式应该如何丢弃你想要的字符串?在这种情况下,您需要使用负前瞻。
标签: javascript regex regex-lookarounds regex-group regex-greedy