用于URL验证的正则表达式

时间:2012-02-15 06:42:49

标签: c# .net 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.It不适用于google./com& amp; www.google.com。

请帮我解决这个问题。

由于

4 个答案:

答案 0 :(得分:48)

不需要正则表达式恕我直言 - 尝试

Uri.IsWellFormedUriString(YourURLString, UriKind.RelativeOrAbsolute)

请参阅MSDN

答案 1 :(得分:6)

将协议部分放在可选组中,即()?

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

答案 2 :(得分:4)

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

bool isValid =(Regex.IsMatch(value,@&#34;(((([az] | \ d | - |。| |〜| [\ u00A0- \ uD7FF \ uF900- \ uFDCF \ uFDF0- \ uFFEF])|(%[\ DA-F] {2})| [\ $&安培;&#39;()* +,=] |:!)* @)(((\ d | [1-9] \ d | 1 \ d \ d | 2 [0-4] \ d | 25 [0-5])(\ d |。[1-9] \ d | 1 \ d \ d | 2 [0-4] \ d | 25 [0-5])(\ d |。[1-9] \ d | 1 \ d \ d | 2 [0-4] \ d | 25 [0-5 ])(\ d |。[1-9] \ d | 1 \ d \ d | 2 [0-4] \ d | 25 [0-5]))|((([AZ] | \ d | [ \ u00A0- \ uD7FF \ uF900- \ uFDCF \ uFDF0- \ uFFEF])|(([AZ] | \ d | [\ u00A0- \ uD7FF \ uF900- \ uFDCF \ uFDF0- \ uFFEF])([AZ] | \ d | - | | |〜| [\ u00A0- \ uD7FF \ uF900- \ uFDCF \ uFDF0- \ uFFEF])([AZ] | \ d | [\ u00A0- \ uD7FF \ uF900- \ uFDCF \ uFDF0- \ uFFEF]))))+(([AZ] |。[\ u00A0- \ uD7FF \ uF900- \ uFDCF \ uFDF0- \ uFFEF])|(([AZ] | [\ u00A0 - \ uD7FF \ uF900- \ uFDCF \ uFDF0- \ uFFEF])([AZ] | \ d | - | | _ |〜| [\ u00A0- \ uD7FF \ uF900- \ uFDCF \ uFDF0- \ uFFEF])< /em>([az]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))).?)(:\d*)?)(/((([az]|\d !| - | | |〜| [\ u00A0- \ uD7FF \ uF900- \ uFDCF \ uFDF0- \ uFFEF])|(%[\ DA-F] {2})| [\ $&安培;& #39;()* +,; =] |:| @)+(/(([AZ] | \ d | - | | |〜| [\ u00A0- \ uD7FF \ uF900- \ uFDCF \ uFDF0- \ uFFEF])|(%[\ DA-F] {2})| [\ $&安培;&#39;()* +,=] |:| @)的)?)?(\? ((([AZ] | \ d | - | | |〜| [\ u00A0- \ uD7FF \ uF900- \ uFDCF \ uFDF0- \ uFFEF])|(%[\ DA-F] {2} )| [\ $&放大器;&#39;()* +,=!] |:??| @)| [\ uE000- \ uF8FF] | / | \)*)(#((([AZ] | \ d | - !| | |〜| [\ u00A0- \ uD7FF \ uF900- \ uFDCF \ uFDF0- \ uFFEF])|(%[\ DA-F] {2})| [\ $&安培;&#39;()* +,=] |:| @)| / | \)*)$&#34));

我正在寻找将近一整天,这是我发现的最好的..这些只是少数有效样本:

  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

答案 3 :(得分:1)

^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?