An Intro to regular expressions, its application and limitations .
A regular expression is an object that decribes a specific pattern of characters, it is matched against a string to see if these is successful match.
1. By assigning a literal expression to a variable.
2. Using a RegExp constructor to create and return a regular expression.
Regular expression using : Literals Notations
A regular expression object using literals is created by assigning a regular expression to a variable.
If you see a regular expression, its a pattern of characters enclosed within forward slashes. flags like i, g and m are used after the forward slash inorder to modify the search pattern.
Table: Regular Expression Flags to Modify the Search Pattern.
|i||To perform a case-insensitive matching|
|g||To perform a global match, i.e to find all matches instead of stopping after the first match.|
|m||Multiline Mode. To match beginning of a line or beginning of a string, and $ is used to match end of a line or end of a string.|
Format and Example: Flags for Modififying Search Patterns.
The Contructor method is used when the regular expression can change throughout the run of the program, if the regular expression is not going to change(i.e hard coded) then the literal notation method is faster.
Inorder to test for a match within an input string, the RegExp object has two methods : the test() method and the exec() method.
Table: Methods of RegExp Object.
|exec()||Searches the string for a match, if a match is found it returns the results in an array, or else a null is returned.|
|test()||It takes a string and returns true if the string contains a match for the regular expression, or else a false is returned.|
The RegExp object's test() method is used to check if the input string matches with the pattern specified by the regular expression.
The RegExp object property lastIndex specifies the position(starting from 0) in the string where the next search would begin.
Incase of a global search(using flag g) the lastIndex property specifies the starting position after the last pattern matched.
The method exec() is used to excute a regular expression on the specified string, it searches the string for a match, if nothing is found it returns a null. But if a match is found the result is returned in an array.