Regular expression for URL

2019-01-14 06:37发布

I have written regex to validate URL which could be either like

All 4 are working

Now, if I am entering in a text like (www.example.com--thisisincorrect), it is allowing me to enter and save into db

The regex that I have used is:

http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

and

([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

Please help!

8条回答
Animai°情兽
2楼-- · 2019-01-14 07:16

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);
查看更多
Luminary・发光体
3楼-- · 2019-01-14 07:17

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
}
查看更多
登录 后发表回答