Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for URL validation

Tags:

c#

.net

regex

I have written regex to validate URL which could be either like

google.com

www.google.com

http://www.google.com

https://www.google.com

I have used

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

It works for http & https.It is not working for google./com & www.google.com.

Please help me to solve this.

Thanks

like image 690
PrateekSaluja Avatar asked Feb 15 '12 06:02

PrateekSaluja


2 Answers

no need for a regex IMHO - try

Uri.IsWellFormedUriString(YourURLString, UriKind.RelativeOrAbsolute)

See MSDN

like image 154
Yahia Avatar answered Oct 01 '22 09:10

Yahia


Put the protocol section in an optional group i.e., ()?:

^((http|ftp|https|www)://)?([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?$
like image 34
Sina Iravanian Avatar answered Oct 01 '22 11:10

Sina Iravanian