A Regular Expression or RegEx is an object that describes a pattern of characters. Regular expressions are used to perform pattern-matching and “search-and-replace” functions on text. –W3 Schools

Regular expressions help us filter or search for a specific pattern or text. Once you learn how to work with regular expressions, you can use that with the language of your choice. In this article we will capture the basics of regular expressions with some examples.

Below Meta Characters can be used to recognize patterns in RegEx

Meta CharacterDescription
. Any Character except new line
\dAll Digit ( 0 to 9 )
\DNot a digit (0-9 )
\wWord character (a-z A-Z 0-9 _)
\WFind a non word character
\sWhite space (space, tab, newline)
\SNot a white space
\bWord boundary
\BNot a word boundary
^Beginning of a string
$End of a string
[ ]Matches the characters in the bracket
[^ ]Matches characters not in bracket
|Either or
( )Creates a group
*0 or more
+1 or more
?0 or one
{ }Exact number
{3 , 5}Range of numbers {min, max}

RegEx Examples

Now that we have seen all the basic meta characters and expressions we can use in RegEx, lets understand them better by decoding some widely used RegEx patterns .

RegEx for Email Validations

Pattern :- ^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$

Description :

^ – indicates that the email should start with the group 1 – ([a-zA-Z0-9_\-\.]+) which in turn says , any character from a-z or A-Z or it can be a number from to 9 or underscore , hyphen or a period. Since its followed by a +, means that this group should appear 0 or more time.

First group should be followed by a @ character

Now lets see the group 2 – ([a-zA-Z0-9_\-\.]+) , its same as that of group 1.

Group 2 is followed by “\.” period and which means that the pattern expected is a period – .

Now the final group , Group 3 – ([a-zA-Z]{2,5})$, specifies any character from a-z or A-Z with a minimum or 2 characters to the maximum of 5 characters and should be an end of the email string.

RegEx for Phone number validations

pattern : ^[2-9]\d{2}-\d{3}-\d{4}$

Description :

This expression matches a hyphen separated US phone number, of the form ANN-NNN-NNNN, where A is between 2 and 9 and N is between 0 and 9.

Matching phone numbers : 800-555-5555 | 333-444-5555 | 212-666-1234

Un Matching numbers : 000-000-0000 | 123-456-7890 | 2126661234

References :