jwegner
jwegner

Reputation: 7423

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

Upvotes: 2

Views: 1778

Answers (1)

alex
alex

Reputation: 7471

hwnd posted the correct answer:

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

Upvotes: 1

Related Questions