Common regular expression that can be used in custom fields

What is Regular Expression (RegEx)?

Regular expressions are sequences of characters that are used to match a certain pattern in a String. However, most of the programming languages provide options to handle regular expressions or commonly called RegEx or regular expression. Besides, it is generally used for finding a part of a string or to validate the input string.

Commonly used RegEx patterns :

Many times we find ourselves trying to find the right RegEx to match the pattern that is required. So, here we will describe about some regular expressions that are most commonly used in our custom field.

1. Password strength validation :

We generally estimate the strength of a Password based on the numeric’s, symbols, and Uppercase alphabets. Regular Expression for strict password validation:

^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[^\w\d\s:])([^\s]){8,16}$

This checks if the string contains one lowercase alphabet, one uppercase alphabet, one number, a symbol, and no space.

2. Email validation :

Validating email is a critical point while validating an HTML form. Since an email is a string that is separated into two parts by @ symbol. A “personal_info” and a domain, that is personal_info@domain. So, the length of the personal_info part may be up to 64 characters long and the domain name may be up to 253 characters. A regular expression for valid email :

^([a-z0-9]+(?:[._-][a-z0-9]+)*)@([a-z0-9]+(?:[.-][a-z0-9]+)*\.[a-z]{2,})$

The personal_info part contains lowercase letters, digits, and characters. The domain name [for example com, org, net, in, us, info] part contains letters, digits, hyphens, and dots as well.

3. URL validation :

URL regex validation is the best way to check if a string is a valid URL or not. Just pass the Regex in the match method to validate the URL.

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

Moreover, the expression checks if the URL starts with HTTP or HTTPS, the symbol://, www. ,  subdomain of length (2, 256), and Domain.

4. Phone number validation :

Phone numbers look different depending on which part of the world you are from. The most common format is:

^([+]?\d{1,3}[-\s]?|)\d{3}[-\s]?\d{3}[-\s]?\d{4}$

The first half of the following expression checks the country code and the other half checks the 10 digits after that.

5. IP address validation :

IP addresses are used on the Internet to identify components connected to a network. Since most computers still use IPv4 addresses. To match an IPv4 IP address:

^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$

The following expression checks if the IP address consists of 32-bit numeric addresses or not. It is written as four decimal numbers (called octets) separated by periods and each number can be written as 0 to 255.