Regular expression is the language to define specific pattern for text data. Javascript supports regular expression. Regular expression is generally used like below. We will look different type of usage examples of regular expression.
var str = "This is an example about regex for poftut.com"; var re = new RegExp( "poftut", "g" ); var result = re.exec(str);
- str is the text data we want to regex.
- re is our regex object to regex.
- re.exec() gets text data and executes regular expression. This will return an array of matched strings which is [“poftut”] in this example
Regex Only Alphabet Characters
We can set a match for alphabet characters like below.
var str = "This is an example about regex for poftut.com"; var re = new RegExp( "[a-zA-Z]", "g" ); var result = re.exec(str);
- re.exec() will return first occurence of the matching character which is T
Not Match Given Characters
We can provide negative match by providing characters.
var str = "This is an example about regex for poftut.com"; var re = new RegExp( "[^a-Z]", "g" ); var result = re.exec(str);
- [^a-Z] means do not match those characters. As expected result will be space character.
Match Any Decimal Digit
We can match decimal digites like below
var str = "This is an example about regex for poftut.com 9"; var re = new RegExp( "[0-9]", "g" ); var result = re.exec(str);
- [0-9] means characters between 0 and 9 which are decimal digits. Results will be 9.
Match Any Lowercase Character
var re = new RegExp( "[a-z]", "g" );
Match Any Uppercase Characters
var re = new RegExp( "[A-Z]", "g" );
Quantifiers
We can set the frequency of regex expression with different operators and we call them quantifiers.
One or More
If we want to look regex expression which occure one or more time we can use + .
var str = "This is an example about regex for poftut.com 9"; var re = new RegExp( "(a)+", "g" ); var result = re.exec(str);
- We match (a)+ where one or more a exists. Result is an array like [“a”,”a”]
Zero or More
Similar to one or more but zero occurence is accepted too. We can use asterisk * for this operation.
Match Only One Character
We can look only one character like a? .
Match Specified Times
We can set minimum and maximum occurence with {} .
var str = "This is an exaample about regex for poftut.com 9"; var re = new RegExp( "a{2,2}", "g" ); var result = re.exec(str);
- Match minum 2 maximum 2 occurence of a which is aa . result will be [ “aa” ]
Match End of Line
We can match by using end of line
var str = "This is an exaample about regex for poftut.com 9"; var re = new RegExp( "9$", "g" ); var result = re.exec(str);
- 9$ means line ends with 9. We get [“9”] as result.
Match Start of Line
We can match by using start of line
var str = "This is an exaample about regex for poftut.com 9"; var re = new RegExp( "^This", "g" ); var result = re.exec(str);
- ^This means line starts with This. We get [“This”] as result.