dimas
dimas

Reputation: 2597

Regex not matching URL

I have regex expression (1) which matches the URL specified below. However I have problem creating a regex for input URL (see not matching). Any ideas how to do this on regex where user can input a URL with combination of http, https or www or even without these three but will still match the URL?

(1)
^(http|https)://www.example.com

(1) Matches
http://www.example.com
https://www.example.com

Not Matching
http://example.com
https://example.com

Should Match
http://www.example.com
https://www.example.com
http://example.com
https://example.com
example.com

Upvotes: 1

Views: 64

Answers (2)

Anshul Rai
Anshul Rai

Reputation: 782

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

Just appended a $ and a \ before .com to nu11p01n73R solution in case you wanted your match to end at .com

Upvotes: 2

nu11p01n73R
nu11p01n73R

Reputation: 26667

Make the https:// and www optional by using ? quantifiers.

^(?:(?:http|https)://)?(?:www\.)?example\.com

Regex Demo

Upvotes: 2

Related Questions