3
votes

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

1
Please use example.com and friends for example domains. I doubt you own domain.com.Quentin

1 Answers

7
votes

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

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