C#:RegEx用于Url验证

时间:2013-03-22 09:35:02

标签: c# regex

我需要一个正则表达式验证网址:

这应该是有效的

http://www.google.com

https://www.google.com

但不是这样:

google.com

www.google.com

我知道这可以用Uri.IsWellFormedUriString完成,但我需要一个正则表达式。找到了几个类似的主题,但不适合我的情况。谢谢!

3 个答案:

答案 0 :(得分:2)

试试这个

 Regex urlchk = new Regex(@"((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,15})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&%_\./-~-]*)?", RegexOptions.Singleline | RegexOptions.IgnoreCase);

答案 1 :(得分:2)

你确定你想要正则表达式而不是这个 - Uri.TryCreate吗?

你也经历过这篇文章 - What is the best regular expression to check if a string is a valid URL?

答案 2 :(得分:1)

(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?