I need a RegEx used in JavaScript to match some URL rules:
- Should start with
http,https,ftp,ftpsormailto:(required) wwwis optionala-z,A-Z,0-9and 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
urlmatches:www.google.com, but it should not, since it has to start withhttp,https,ftp,ftpsormailto:(required). I just putted the?after the(s), so only this should be optional. Why does this not work?This
urlstill does not match:http://intranet/index.htmlbut I thought, I have the right rule for special chars.:-/.
TESTING: List of URL which should match:
https://www.sample.comhttps://www.sample-sample.comhttp://www.sample.comhttp://www.sample-sample.comhttps://sample-sample.comhttp://sample-sample.comftps://sample-sample.com,ftp://sample-sample.comftps://sample.sample.com:3000ftp://sample.sample.com:3000http://intranet/index.htmlmailto:sample@sample.com
List of URL should not match:
- www.google.com
Any inputs?