URL/String 的正则表达式 - 如果协议 return 为假

Regex for URL/String - If protocol return false

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

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

,它 return 为真
^(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);

这个也是 return 正确的。

此处演示

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

正则表达式是否可行?

如果您只是想否定正则表达式:

function doesMatch(string) {
 return !/^http(s):\/\/(?:www)?/.test(string);
}

[
 'https://www.xxzx.com/xxx.aspx',
 'http://www.xxxx.com',
 'https://xxxx.com',
 'http://xxxx.com',
 'https://aaaa.com',
 'aaaa.com'
].forEach(s => console.log(doesMatch(s)));

In your example code, re.test(url) returns false ,因为该字符串中不存在 http 或 https。 在 url2 (ie..'https://www.xxzx.com/xxx.aspx') 中,存在 https,因此它返回 true。

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

^(?!(?: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)))

可能可以使用正则表达式,但除非您必须使用正则表达式,否则您应该使用 URL class:

let HTTP_URL = 'https://www.xxzx.com/xxx.aspx'
let HTTPS_URL = 'https://www.xxzx.com/xxx.aspx'
let FTP_URL = 'ftp://www.xxzx.com/xxx.aspx'
let GOOD_PROTOCOL = 'mysql://www.xxzx.com/xxx.aspx'
let GOOD_INPUT = '129.123.12.123'

function test_url(url) {
    let bad_protocols = ['http:', 'https:', 'ftp:']
  try {
        var parsed = new URL(url)
  } catch {
    return true
  }
  return (!bad_protocols.contains(parsed.protocol))
}

test_url(HTTP_URL) //false
test_url(HTTPS_URL) //false
test_url(FTP_URL) //false
test_url(GOOD_PROTOCOL) //true
test_url(GOOD_INPUT) //true

这个表达式也可能有效,它会允许你想要的输入并使所有其他 URL 失败,你也可以简单地添加到它的字符列表,还有什么可能不希望开始:

^([^http|s|ftp|www|\/\/|])*

通过

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
//www.xxxx.com

您可以在 this link 中 test/modify/change 它。

正则表达式描述图

此图显示了表达式的工作原理,您可以在此 link 中可视化其他表达式:

性能测试

此 JavaScript 片段显示了使用简单的 100 万次 for 循环时该表达式的性能。

const repeat = 1000000;
const start = Date.now();

for (var i = repeat; i >= 0; i--) {
 const string = 'xxxx.xxxx.xxxx';
 const regex = /(^([^http|s|ftp|www|\/\/|])*)/gm;
 var match = string.replace(regex, "");
}

const end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match  ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test.  ");