Tyler
Tyler

Reputation: 1285

Using RegEx to match domain.com and www.domain.com but NO OTHER subdomains?

Sorry if this has been asked elsewhere, I've been looking and can't find it for the life of me. I am attempting at tackling regular expressions, I've ALWAYS had problems with the more advanced scenarios... well, others find them quite easy, so maybe there's something wrong with me.

Anyway, I am attempting to write a RegEx that matches www.domain.com OR domain.com but NO OTHER SUBDOMAINS or anything. The only two strings I want to pass the regex are "domain.com" and "www.domain.com" and I haven't been able to find exactly what I am looking for other than including all subdomain matching, which I find easy.

The closest I have come is this: regex for matching something if it is not preceded by something else but in that case its failing only for one preceding string, I want it to succeed for only one preceding string/subdomain. Note, "domain.com" will always be static, meaning it will always be that exact string "domain.com" not various domains.

Thanks so much for shedding light on this!

Tyler

Upvotes: 3

Views: 4593

Answers (1)

Quentin
Quentin

Reputation: 943510

Just put the optional part in a non-capturing group, and make it optional.

/^(?:www\.)?example.com$/

Upvotes: 7

Related Questions