用于URL验证的正则表达式

本文关键字:正则表达式 验证 URL 用于 | 更新日期: 2023-09-27 18:24:32

我已经编写了regex来验证URL,它可以像一样

google.com
www.google.com
http://www.google.com
https://www.google.com

我用过

Regex urlRx = new Regex(@"^(http|ftp|https|www)://(['w+?'.'w+])+([a-zA-Z0-9'~'!'@'#'$'%'^'&'*'(')_'-'='+'''/'?'.':';''',]*)?$", RegexOptions.IgnoreCase);

它适用于http&https。这对谷歌不起作用/com&www.google.com.

请帮我解决这个问题。

感谢

用于URL验证的正则表达式

不需要正则表达式IMHO-尝试

Uri.IsWellFormedUriString(YourURLString, UriKind.RelativeOrAbsolute)

请参阅MSDN

将协议部分放入可选组,即()?:

^((http|ftp|https|www)://)?(['w+?'.'w+])+([a-zA-Z0-9'~'!'@'#'$'%'^'&'*'(')_'-'='+'''/'?'.':';''',]*)?$

我从jquery.validation得到了这段代码(我做了一些编辑)

bool isValid=(Regex.IsMatch(value,@)?(((([a-z]|''d|-|.||~|[''u00A0-''uD7FF''uF900-''uFDCF''uFDF0-''uFFEF])|(%[''da-f]{2})|[!''$&'()*+,;=]|:)*@)?''d|1''d''d|2[0-4]''d|25[0-5])|[''u00A0-''uD7FF''uF900-''uFDCF''uFDF0-''uFFEF])([a-z]|''d|-|.||~|[''u00A0-''uD7FF''uF900-''uFDCF''uFDF0-''_FFE])+(([a-z]|[''u00A0-''uD7FF''uF900-''uFDCF''uFDF0-''uFFEF])|(([a-z]|[''u 00A0-''_D7FF''uF900-''u FDCF''uFDF0-''_FFEF】)([a-z]|''d|-|.|_|~|[''u00A0-''uF7FF''uF900-''uFDCF''u FDF0-'''' uFFEFE])''uF900-''uFDCF''uFDF0-''uFFEF]))(:''d*)?)(/((([a-z]|''d|-|.||~|[''u00A0-''uD7FF''uF900-''uFDCF''uFDF0-''uFFEF])|(%[''da-f]{2})|[!''$&'()*+,;=]|:|@)+[''da-f]{2})|[!''$&'()*+,;=]|:|@))?(''?((([a-z]|''d|-|.||~|[''u00A0-''uD7FF''uF900-''uFDCF''uFDF0-''uFFEF])|(%[''da-f]{2})|[!''$&'()*+,;=]|:|@)|[''uE000-''uF8FF]|/|''?)*)?(#((([a-z]|''d|-|.||~|[''u00A0-''uD7FF''uF900-''uFDCF''uFDF0-''uFFEF])|(%[''da-f]{2})|[!''$&'()*+,;=]|:|@)|/|''?)*)$"));

我几乎找了一整天,这是我找到的最好的。。这些只是为数不多的有效样本:

  1. example.com
  2. example.com.ph
  3. www.example.com
  4. http://example.com
  5. https://example.com
  6. http://www.example.com
  7. ftp://example.com
  8. example.com/doc
  9. www.example.com/doc
  10. http://example.com/doc
  11. http://example.com/questions/12576252/convert-javascript-regex-to-c-sharp-regex-for-email-validation
  12. http://www.example.com/wpstyle/?p=364
  13. http://userid:password@example.com:8080
  14. https://www.example.com/foo/?bar=baz&inga=42&quux
  15. LDAP://ad1.cc.uq.edu.ph
^(http|http(s)?://)?(['w-]+'.)+['w-]+[.com|.in|.org]+('['?%&=]*)?