regular expression to match URL

Regular Expression to Match URL Path

Sometimes you may need to developer a regular expression to find a URL path from a string, or text that you have received. This can be a problem in almost every programming language such as Python, JavaScript, etc. In this article, we will see how to create regex to match URL path. You can keep them handy for whenever you need it. It is useful in form validation, input verification, and URL extraction from text.


Regular Expression to Match URL Path

Here is the regular expression to match URL without protocol HTTP/HTTPS.

[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)

If you also want to include the protocol HTTP/HTTPS, modify the above expression as shown below.

https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)

The above patterns work for both www and non-www versions since we are using (www\.)? which makes www. optional. Then we have domain that can be from 1 to 256 characters.

Here is a simple example to test if a given string is a URL or not.

var expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var test = 'www.facebook.com';

if (test.match(regex)) {
  alert("string contains URL");
} else {
  alert("string does not contain URL");
}

In the above code, we use /gi suffix for expression variable to specify that it is a regular expression. Then we use RegExp() constructor obtain a regex from expression. We match() function on our test string, using this regular expression. If the test string matches regex it returns true, else it returns false.

In this article, we have learnt how to use regular expressions to match URL. You can use them in most programming languages such as Python, PHP, Java, JavaScript, etc. It is also useful if you want to validate input strings for URLs.

Also read:

How to Split String Every Nth Character in Python
How to Reverse/Invert Dictionary Mapping in Python
How to Sort List of Tuples by Second Element in Python
How to Get Key With Max Value in Dictionary
How to Configure Python Flask to be Externally Visible

Leave a Reply

Your email address will not be published. Required fields are marked *