biox
biox

Reputation: 1566

Match base url regex

Examples:

http://example.com ---> http://example.com
ftp://username:[email protected] ---> ftp://username:[email protected]
http://example.com/path/to/somehwere ---> http://example.com
http://example.co.uk ---> http://example.co.uk
example.co.uk ---> example.co.uk
example.co.uk?user=John&pass=1234 ---> example.com.uk

I tried this:

.*?(:\/{2})?.*?(?=\/|$|\?)

its working for the urls without protocols but cause of the (?=\/|$|\?) it stops at http:

Cany you help me fix my regex? or suggest better?

Upvotes: 7

Views: 12698

Answers (2)

anubhava
anubhava

Reputation: 785266

This lookahead based regex should for you:

^.+?[^\/:](?=[?\/]|$)

RegEx Demo

Lookahead assertion (?=[?\/]|$) makes sure to stop matching when next character is / or ? or there is line end.

Upvotes: 17

gpmurthy
gpmurthy

Reputation: 2427

Consider the following Regex...

(http://|ftp://|https://)?[^/\?]*$

Good Luck!

Upvotes: 2

Related Questions