ralphowino
ralphowino

Reputation: 539

Regex match domain name without www and keep website.com still intact

I have this regex

^(?:http(?:s)?://)?(?:www(?:[0-9]+)?\.)

to strip off the www and http(s):// part of any domain name and give just the domain name. It works with:

But when used with a domain name starting with letter w it strips the w off

Any ideas on how to make it better? Please test it with this data set http://regexr.com/3abl2

Thanks

Upvotes: 2

Views: 3675

Answers (2)

David Faber
David Faber

Reputation: 12485

I think you want something like this:

^(?:https?:\/\/)?(?:www\.)?(.*)$

Please see this Regex Demo for examples and explanation.

UPDATE It looks like you also want to omit www0, www1, etc.? Then you'll want this:

^(?:https?:\/\/)?(?:www[0-9]*\.)?(.*)$

Please see updated demo here.

Upvotes: 3

nu11p01n73R
nu11p01n73R

Reputation: 26667

  • Drop the part (?:[0-9]+)?.) from the regex

  • Add optional quantifier ? to www. Matches zero or one www

The regex can be written as

^(?:http(?:s)?:\/\/)?(?:www)?

Regex Demo

Upvotes: 0

Related Questions