简体   繁体   English

JS 中的 RegExp 负前瞻

[英]RegExp Negative Lookahead In JS

I am trying to write a RegExp that will match all subdomains of a site ASIDE from one.我正在尝试编写一个正则表达式,它将与一个站点的所有子域相匹配。 I think that the best way to do this is with a lookahead, and I think I'm pretty close.我认为做到这一点的最好方法是向前看,我认为我已经很接近了。

I will use amazon.com as an example.我将以 amazon.com 为例。 test.amazon.com will be the subdomain I want to avoid. test.amazon.com 将是我要避免的子域。

So far I've got this:到目前为止,我有这个:

var regexp = new RegExp("https?://(?!test\.)([^/]+\.)?amazon\.com/.*")

However, it seems that the (?.test.) will break ANY subdomain that begins with "test".但是,似乎 (?.test.) 会破坏任何以“test”开头的子域。 My hope was that the \.我的希望是\. would force the RegExp to only fail if there was a period directly following "test".将强制 RegExp 只有在“测试”之后有一段时间才会失败。 This doesn't seem to be the case.情况似乎并非如此。

var regexp = new RegExp("https?://(?!test\.)([^/]+\.)?amazon\.com/.*")

regexp.test("https://amazon.com/")
true //Passes Correctly

regexp.test("https://www.amazon.com/")
true //Passes Correctly

regexp.test("https://atest.amazon.com/")
true //Passes Correctly

regexp.test("https://test.amazon.com/")
false //Fails Correctly

regexp.test("https://tester.amazon.com/")
false //Fails Incorrectly

hwnd发表了正确答案:

https?://(?!test)([^.]+\\.)?amazon\\.com/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM