用于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.
请帮我解决这个问题。
感谢
不需要正则表达式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})|[!''$&'()*+,;=]|:|@)|/|''?)*)$"));
我几乎找了一整天,这是我找到的最好的。。这些只是为数不多的有效样本:
- example.com
- example.com.ph
- www.example.com
- http://example.com
- https://example.com
- http://www.example.com
- ftp://example.com
- example.com/doc
- www.example.com/doc
- http://example.com/doc
- http://example.com/questions/12576252/convert-javascript-regex-to-c-sharp-regex-for-email-validation
- http://www.example.com/wpstyle/?p=364
- http://userid:password@example.com:8080
- https://www.example.com/foo/?bar=baz&inga=42&quux
- LDAP://ad1.cc.uq.edu.ph
^(http|http(s)?://)?(['w-]+'.)+['w-]+[.com|.in|.org]+('['?%&=]*)?