What is Regex

Regex is abbreviation of the Regular Expression. Regular Expression is an expression that can be use in many programming languages and finds sections that match certain rules in numeric and string content.

Where to Use


Many programming languages, operating system commands, database queries and search applications uses Regular Expression. We are going to use it on HTML inputs for specifical input type like Social ID, phone number, email, credit card number and validation date etc.

How to Use

Regex is abbreviation of the Regular Expression. Regular Expression is an expression that can be use in many programming languages and finds sections that match certain rules in numeric and string content.

Code Sample


You can define a Regular Expression which consists of a pattern enclosed between slashes or just define a Regular Expression as an object.

var re = /ab+c/;

//or

var re = new RegExp('ab+c');

Rules


Each language has different rules for describing Regular Expressions. We are going to analyze it for JS.

Token Description Sample
* Repeating 0 or more of previous token. a* --> ,a,aa,aaa
+ Repeating 1 or more of previous token. a+ --> a,aa,aaa
() Making group. (aa)+ --> aa,aaaa,aaaaaa
[] One of the characters within the specified range. [1-4] --> 1,2,3 or 4
[^] Except One of the characters within the specified range. [^1-4] --> Except 1,2,3 and 4
\s Space character. \s+ --> , ,
\S Except space character. \S+ --> abc,123,a1b2c3
\d All numeric characters. \d+ --> 1,32,512,1024
\D Except all numeric characters. \D+ --> a,bc,def,qwerty
\w All characters used in words. \w+ --> Bedirhan
{} Number of previous characters or groups to repeat. [1-4]{3} --> 111,234,134

Examples

There some examples for practice.

Basic Patterns


// ^ character for beginning and $ character for end of the string.

// All Numbers

var re = new RegExp('^\d+$');

// 11 Range Phone Number

var re = new RegExp('^([0-9]{11})$');

// Simple Email Pattern : bedirhan.yildirim@stu.fsm.edu.tr

var re = new RegExp('^\S+@\S+\.\S+$');

// Detail Email Pattern : bedirhan.yildirim@stu.fsm.edu.tr

var re = new RegExp('^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$');

// Lower Case min 1, max 10 character

var re = new RegExp('^[a-z]{1,10}$');

// Upper Case

var re = new RegExp('^[A-Z]$');

// Date Format (dd/mm/yyyy)

var re = new RegExp('^([0-9]){2}(\/|-){1}([0-9]){2}(\/|-){1}([0-9]){4}$');