【问题标题】:C#: RegEx for Url validation [duplicate]C#:用于 URL 验证的正则表达式 [重复]
【发布时间】:2013-03-22 09:35:01
【问题描述】:

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

这应该是有效的

http://www.google.com

https://www.google.com

但不是这个:

google.com

www.google.com

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

【问题讨论】:

  • I know this can be done with Uri.IsWellFormedUriString for example but I need a regex。请问为什么需要正则表达式?因为每次我听到有人需要正则表达式时,智者的话都会在我耳边回荡:Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems
  • 请参阅this...
  • 因为该逻辑已经使用正则表达式实现,用于验证不同类型的输入数据,但它不会将 www.google.com 和 goodgle.com 视为无效 url。将其更改为使用 Uri.IsWellFormedUriString 将需要一些重构,我现在将修复 reg ex。

标签: c# regex


【解决方案1】:

您确定要使用正则表达式而不是这个 - Uri.TryCreate

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

【讨论】:

    【解决方案2】:
    (http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?
    

    【讨论】:

      【解决方案3】:

      试试这个

       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);
      

      【讨论】:

        猜你喜欢
        • 2011-05-16
        • 2013-05-02
        • 2011-05-11
        • 2017-07-25
        • 2012-02-22
        • 1970-01-01
        • 2011-06-17
        • 1970-01-01
        相关资源
        最近更新 更多