I need a RegEx used in JavaScript to match some URL rules:
- Should start with
http
,https
,ftp
,ftps
ormailto:
(required) www
is optionala-z
,A-Z
,0-9
and some special characters.:-/
are allowed
Since I'm not that familiar with RegEx I tried to use this one found in an answer (second answer @foufos): What is a good regular expression to match a URL?
/^(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9/]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9/]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9/]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})
Now this RegEx matches all links I need except two:
e.g. http://intranet/index.html
mailto:sample@sample.com
So I tried to modify it and added the mailto:
rule:
/^((http(s)?)|(ftp(s)?):\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,}|(mailto:){1}([\w\.]+)\@{1}[\w]+\.[\w]{2,})\s$/gm;
At the moment, two things are not working:
This
url
matches:www.google.com
, but it should not, since it has to start withhttp
,https
,ftp
,ftps
ormailto:
(required). I just putted the?
after the(s)
, so only this should be optional. Why does this not work?This
url
still does not match:http://intranet/index.html
but I thought, I have the right rule for special chars.:-/
.
TESTING: List of URL
which should match:
https://www.sample.com
https://www.sample-sample.com
http://www.sample.com
http://www.sample-sample.com
https://sample-sample.com
http://sample-sample.com
ftps://sample-sample.com
,ftp://sample-sample.com
ftps://sample.sample.com:3000
ftp://sample.sample.com:3000
http://intranet/index.html
mailto:sample@sample.com
List of URL
should not match:
- www.google.com
Any inputs?