Regular Expressions - JavaScript and PHP (Email & URL Regex)

Regular expressions, also shortened as regex, are used to find, extract, match, validate, or replace specific patterns in a string. Learn how to perform common string checks with simple and practical regex examples.

Regular Expressions

What is a Regular Expression?

A regex (regular expression) is a sequence or pattern of characters used to find part of a string that matches a specific pattern. This pattern search can be for just extracting a certain portion of a string, replacing it with something else, or validating the string for a specific format. Regular expressions are used in many applications like Notepad++ and Microsoft Word. Web developers also use them when developing an application to use validate user inputs, extracting information, and replacing text. This post will further explain how to create regular expressions with basic and practical use examples.

 

Regular Expressions in PHP & JavaScript

Regular expressions are written with slight changes in syntax when it comes to web development languages. The examples used in this post use PHP regex and JavaScript regex patterns. Both languages use forward slashes (/) at the start and end to define a regex pattern, and the implementation and methods used in both languages are also different.

As explained in the official JavaScript Regular Expressions documentation, it provides its own list of functions to find, replace or validate certain patterns. Whereas PHP has its own built-in PCRE(Perl Compatible Regular Expressions) functions to work with different string patterns.

 

How to Write a Regular Expression?

Although the basic syntax of regular expressions is similar across different languages and applications, but there are some differences in syntax, feature support, and how they are used depending on the regex engine used. Let's take a look at special characters and quantifiers to have a basic understanding of regex syntax:

  • ^ regex quantifier indicates the start of a pattern in a string or line. For example, "^hello" would mean the string or line should start with "hello".
  • $ regex quantifier indicates the end of a pattern in a string or line. For example, "bye$" would mean the string or line must end with "bye".
  • * regex quantifier indicates zero or more occurrences of the preceding character or group of characters. For example, "123*A" would mean the string has a "123" number and "A" could appear any number of times or not at all.
  • + regex quantifier indicates the preceding character or group of characters occurs at least one time and could occur more than one time. For example, "abc+" would mean the string should have "ab" and "c" at least one time, or more. So "abc" and "abccc" both will pass the match, but only "ab" will not.
  • ? regex quantifier indicates zero or one occurrences of the preceding character or group of characters. For example, "https?" would mean the "s" at that position can occur only once or can be missing. So "htpp" and "https" both will pass the match, but "httpss" will not.
  • () regex captures a group of characters. For example, "(www\.)" will mean the string should be "www." as a whole group. Regex groups are also used for references in the following patterns.
  • [] regex indicates a set of characters or any of the characters inside brackets. For example, "123[a-zA-z]" will mean the string should be "123" and any alphabet should be either lowercase or uppercase. So "123H" will be a correct match.
  • {} regex limits the occurrence of the preceding character or group of characters to a specific number or between a specific range. For example, "a{2,4}" will mean the letter "a" should appear between two and four times. In this case, "aa", "aaa", and "aaaa" will be valid matches.
 

Regular Expression Examples:

Now that we know what different quantifiers and characters mean in a regex, lets understand it further with a few examples. The following table shows the combination of different quantifiers, meta-characters, and character classes to form basic regular expressions. This table can be used as a quick reference for writing regular expressions.

ExpressionDefinitionExampleSample
^Start of string/line/^abc/abcword
$End of string/line/abc$/wordabc
\dAny digit /word\d/word5
\wAny alphanumeric or underscore/123\w/123Z
[0-9]Numbers from 0 to 9 /word[0-9]/word1
[a-z]Letters from a to z/123[a-z]/123a
[A-Z]Letters from A to Z/123[A-Z]/123W
+Minimum one occurrence /\d+/123456
*Zero or more occurrences/\d+A*/123AAA or 123
?Zero or one occurrence/\d+ab?c/123abc or 123ac
.Any character that is not a line break/x.z/xyz
{3}Exactly three occurrences/a{3}/aaa
{2,4}Minimum two and maximum four occurrences/a{2,4}/aa
{2,}Two or more occurrences/\w{2,}/word_word

Commonly Used Regular Expressions:

Web developers often need to use regex to find, match, replace, or validate strings. The following are mostly used regular expressions in JavaScript and PHP. These regular expressions are related to checking for only numbers, alphabets, URL format, and email address format.

 

Regular Expression to Validate Only Digits:

This is one of the use cases where developers use a number regex pattern to check or verify if a string contains only numbers/digits:

ExpressionSampleResult
/^[0-9]+$/123456Pass
123abcFail
 

Regular Expression to Validate Only Alphabets:

The following table shows an alphabet regex pattern that applications use to verify and validate only alphabets:

ExpressionSampleResult
/^[a-zA-Z]+$/abcXYZPass
abcXYZ12Fail
 

Regular Expression to Validate an Email Address:

This is another most common use case when applications use email validation regex to verify and validate email format:

ExpressionSampleResult
/^[\w\-\.]+\@[a-zA-Z0-9]+\.[a-zA-Z]{2,4}$/[email protected]Pass
user@domainFail
userdomain.comFail
 

Regular Expression to Validate a URL:

Sometimes web applications also use URL regular expression patterns to verify and validate a URL for a specific format, whether it uses http or https protocol, or if it is using ftp protocol:

ExpressionSampleResult
/^((https?|ftp):\/\/)(www\.)?[\w\-]+\.[a-z]{2,4}\/?$/https://domain.comPass
http://domain.comPass
http://www.domain.comPass
www.domain.comFail

Regular expressions are a effective technique to find, replace, match, and validate strings using different patterns. Even though the methods used in JavaScript and PHP are different, they use the same concept to perform the same checks. They be used more effectively in web application with a proper understanding of patterns, quantifiers, and meta-characters.