简体   繁体   中英

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. test.amazon.com will be the subdomain I want to avoid.

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". My hope was that the \. would force the RegExp to only fail if there was a period directly following "test". 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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