用于URL验证的正则表达式

Pra*_*uja 15 .net c# regex

我写了正则表达式验证URL,可能就像

google.com

www.google.com

http://www.google.com

https://www.google.com
Run Code Online (Sandbox Code Playgroud)

我用过

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

它适用于http和https.It不适用于google./com和www.google.com.

请帮我解决这个问题.

谢谢

Yah*_*hia 48

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

Uri.IsWellFormedUriString(YourURLString, UriKind.RelativeOrAbsolute)
Run Code Online (Sandbox Code Playgroud)

请参阅MSDN

  • **小心**使用它作为验证URL的唯一方法,因为它允许使用诸如`javascript:alert('邀请来攻击我')之类的URI; (6认同)

Sin*_*ian 6

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

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

  • `System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^((http|ftp|https|www)://)?([\w+?\.\w+])+( [a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\ '\,]*)?$");` (3认同)