Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for URL

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

  • example.com

  • www.example.com

  • http://www.example.com

  • https://www.example.com

All 4 are working

Now, if I am entering in a text like (www.example.com--thisisincorrect), it is allowing me to enter and save into db

The regex that I have used is:

http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)? 

and

([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)? 

Please help!

like image 437
xorpower Avatar asked Apr 19 '11 13:04

xorpower


People also ask

What is a URL regular expression?

URL regular expressions can be used to verify if a string has a valid URL format as well as to extract an URL from a string. Discover UI Bakery – an intuitive visual internal tools builder.

How do you match a URL in regex?

@:%_\+~#= , to match the domain/sub domain name. In this solution query string parameters are also taken care. If you are not using RegEx , then from the expression replace \\ by \ . Hope this helps.

How do you validate a URL?

When you create a URL input with the proper type value, url , you get automatic validation that the entered text is at least in the correct form to potentially be a legitimate URL. This can help avoid cases in which the user mis-types their web site's address, or provides an invalid one.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.


1 Answers

You don't need a regex for URLs, use System.Uri class for this. E.g. by using Uri.IsWellFormedUriString method for this:

bool isUri = Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute); 
like image 163
Oleks Avatar answered Sep 30 '22 00:09

Oleks