I have written regex to validate URL which could be either like
example.com
www.example.com
http://www.example.com
This works for me:
string pattern = @"^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$";
Regex regex = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
string url= txtAddressBar.Text.Trim();
if(regex.IsMatch(url)
{
//do something
}
This is to support both http, https as optional and validate blank space is not included in url.
this.isValidURL = function (url) {
if (!url) return false;
const expression = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/gm;
return url.match(new RegExp(expression));
}
You don't need a regex for URLs, use System.Uri
class for this. E.g. by using Uri.IsWellFormedUriString method for this:
bool isUri = Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute);
Best Regex:
private bool IsUrlValid(string url)
{
string pattern = @"^(http|https|ftp|)\://|[a-zA-Z0-9\-\.]+\.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]$";
Regex reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
return reg.IsMatch(url);
}