Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex expression for valid website link

Tags:

regex

In my asp.net application, i need to validate the text for a valid website link. I want to use the regular expression validator for that. Anyone with any idea of how to validate the weblink user regex.

like image 333
Ankit Avatar asked Sep 16 '10 12:09

Ankit


People also ask

How do you check if a URL is valid?

You can use the URLConstructor to check if a string is a valid URL. URLConstructor ( new URL(url) ) returns a newly created URL object defined by the URL parameters. A JavaScript TypeError exception is thrown if the given URL is not valid.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What is a valid URL string?

A string is a valid URL potentially surrounded by spaces if, after stripping leading and trailing whitespace from it, it is a valid URL. A string is a valid non-empty URL potentially surrounded by spaces if, after stripping leading and trailing whitespace from it, it is a valid non-empty URL.


1 Answers

try this -

^(?:ftp|http|https):\/\/(?:[\w\.\-\+]+:{0,1}[\w\.\-\+]*@)?(?:[a-z0-9\-\.]+)(?::[0-9]+)?(?:\/|\/(?:[\w#!:\.\?\+=&%@!\-\/\(\)]+)|\?(?:[\w#!:\.\?\+=&%@!\-\/\(\)]+))?$

Explained each step below -

^                                   # Start at the beginning of the text  
(?:ftp|http|https):\/\/              # Look for ftp, http, or https  
(?:                                  # Username:password combinations (optional)    
  [\w\.\-\+]+                        # A username    
  :{0,1}                             # an optional colon to separate the username and password    
  [\w\.\-\+]*@                       # A password  
)?  
(?:[a-z0-9\-\.]+)                    # The domain limiting it to just allowed characters  
(?::[0-9]+)?                         # Server port number  
(?:                                  # The path (optional)    
  \/|                                # a forward slash    
  \/(?:[\w#!:\.\?\+=&%@!\-\/\(\)]+)| # or a forward slash followed by a full path    
  \?(?:[\w#!:\.\?\+=&%@!\-\/\(\)]+)  # or a question mark followed by key value pairs   
)?$
like image 147
Sachin Shanbhag Avatar answered Oct 01 '22 16:10

Sachin Shanbhag