【问题标题】:How to match URL in c#?如何在 C# 中匹配 URL?
【发布时间】:2010-11-22 08:05:51
【问题描述】:

我发现了许多关于如何在 PHP 和其他语言中匹配特定类型的 URL 的示例。我需要匹配我的 C# 应用程序中的任何 URL。这个怎么做?当我谈论 URL 时,我指的是指向任何站点或站点和子目录上的文件的链接等等。

我有这样的文字:“转到我的可怕网站 http:\www.google.pl\something\blah\?lang=5”,否则我需要从此消息中获取此链接。链接只能以 www 开头。也是。

【问题讨论】:

  • 可能你的意思是使用正斜杠,因为你永远不会匹配带有反斜杠的 URL,因为你混淆了 Microsoft\Windows Land 和 Unix/WWW Land。

标签: c# regex url


【解决方案1】:

我不确定您要问什么,但一个好的开始是 Uri 类,它将为您解析 url。

【讨论】:

  • 这可能更具体:例如:var myUri = null; Uri.TryCreate(str, UriKind.Absolute, out myVar);并检查 myUri 是否从 null 变为非 null。
【解决方案2】:

如果你需要测试你的正则表达式来查找 URL,你可以试试这个资源

http://gskinner.com/RegExr/

它会在你编写时测试你的正则表达式。

在 C# 中,您可以使用正则表达式,例如:

Regex r = new Regex(@"(?<Protocol>\w+):\/\/(?<Domain>[\w@][\w.:@]+)\/?[\w\.?=%&=\-@/$,]*");
// Match the regular expression pattern against a text string.
Match m = r.Match(text);
while (m.Success) 
{
   //do things with your matching text 
   m = m.NextMatch();
}

【讨论】:

  • +1 : 虽然你忘了在字符串前面添加@符号。
  • @Rumplin:你能解释一下你得到的错误吗?如果我尝试使用 gskinner,正则表达式会正确匹配 test.com 或者您是否打算将整个字符串与 '' 匹配?
  • 您必须查看实际的 url,而不是显示的那个。 Stackoverflow 更正链接... 'h t t p : // h t t p : //' 没有空格
【解决方案3】:
Regex regx = new Regex("http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase); 

【讨论】:

    【解决方案4】:

    这是为 URL 定义的一个。

    ^http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$
    

    http://msdn.microsoft.com/en-us/library/ms998267.aspx

    【讨论】:

      【解决方案5】:

      这将返回在“yourStringThatHasUrlsInIt”中找到的所有匹配项的匹配集合:

      var pattern = @"((ht|f)tp(s?)\:\/\/|~/|/)?([w]{2}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?";
      var regex = new Regex(pattern);
      var matches = regex.Matches(yourStringThatHasUrlsInIt);
      

      返回将是一个“MatchCollection”,您可以在此处阅读更多信息:

      http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchcollection.aspx

      【讨论】:

        【解决方案6】:

        微软有一些正则表达式的好页面......这就是他们所说的(效果也很好)

        ^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$
        

        http://msdn.microsoft.com/en-us/library/ff650303.aspx#paght000001_commonregularexpressions

        【讨论】:

        • 那个不包括url后面的查询字符串。它停在第一个“=”字母处。要解决此问题,只需添加单个字符“=”,使其以“....&%\$#_=]*)?$”结尾。此外,该正则表达式模式不会在字符串中找到 url。它只会告诉您该字符串是否为 url。要找到它,请在开头省略“^”,在结尾省略“$”。 Regex.Matches(text, pattern) 然后应该返回文本中的所有 url。
        • 是否包含邮件地址?
        • 这种情况失败:example.com:81/path/index.php?query=toto+le+heros#top 可以用 (ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\ w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/ \\\+&%\$#=_]*)?它也不适用于包含 username@hostname 的 url
        【解决方案7】:
                  //This code return (protocol://)host:port from URL
        
                  //Commented URL's with different protocols. Just uncomment to test.
                  //string url = "http://www.contoso.com:8080/letters/readme.html";
                  //string url = "ftp://www.contoso.com:8080/letters/readme.html";
                  //string url = "l2tp://1.5.8.6:8080/letters/readme.html";
                  string url = "l2tp://1.5.8.6:8080/letters/readme.html";
        
                  string host = "";//empty string with host from url
                        //protocol, (ip/domain), port
                  host = Regex.Match(url, @"^(?<proto>\w+)://+?(?<host>[A-Za-z0-9\-\.]+)+?(?<port>:\d+)?/", RegexOptions.None, TimeSpan.FromMilliseconds(150)).Result("${proto}://${host}${port}");
                        //(ip/domain):port without protocol. If HTTPS board loading images from HTTP host.
                  //host = Regex.Match(url, @"^(?<proto>\w+)://+?(?<host>[A-Za-z0-9\-\.]+)+?(?<port>:\d+)?/", RegexOptions.None, TimeSpan.FromMilliseconds(150)).Result("${host}${port}");
        
                  Console.WriteLine("url: "+url+"\nhost: "+host); //display host
        

        https://rextester.com/PVSO54371

        【讨论】:

          【解决方案8】:

          你也可以使用https://github.com/d-kistanov-parc/DotNetUrlPatternMatching

          该库允许您将 URL 与模式匹配。

          它是如何工作的:

          • 一个网址格式被分成几部分
          • 每个非空部分都与 URL 中的相似部分相匹配。

          您可以指定通配符 * 或 ~ 其中 * 是组内的任何字符集(方案、主机、端口、路径、参数、片段) 其中 ~ 组段中的任何字符集(主机、路径)

          只提供您关心的部分网址。遗漏的部分将匹配任何东西。例如。如果您不关心主机,请忽略它。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-01-14
            • 2016-08-26
            • 2017-11-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-07-18
            相关资源
            最近更新 更多