Introduction:
This post is to know regular expression, see usage in sample examples using JavaScript. Plan is to update this post every time a regular expression is solved. Considering this as a quick hand out to refresh memories as well as a list regular expression which are encountered at some point of development life time.
What is regular expression:
A regular expression is a sequence of characters that forms a search pattern to match a combination in strings. In JavaScript regular expression is an object which can be created explicitly or implicitly.
Regular expression creation:
Option-01: implicit way -
var regExp = /[0-9]/;
Option-02: explicit way-
var regExp = new RegExp('[0-9]');
Note: better to use option-01 as option-02 has implication on execution speed.
Various patterns:
1. Direct match - /direct/. This pattern will find a match in string 'Looking for a direct match' but not in 'Misspelled the word diract'.
2. Special characters -
Regular Expression properties:
Methods related to regular expression:
Regular expression with flags:
Syntax: /regular expression/flag;
Flags:
i - case ignore search
g - global search
m - multi line search
Examples:
1. Replace all instances of e or E in a String - /e|E/g.
2.
Resources:
1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
2.
This post is to know regular expression, see usage in sample examples using JavaScript. Plan is to update this post every time a regular expression is solved. Considering this as a quick hand out to refresh memories as well as a list regular expression which are encountered at some point of development life time.
What is regular expression:
A regular expression is a sequence of characters that forms a search pattern to match a combination in strings. In JavaScript regular expression is an object which can be created explicitly or implicitly.
Regular expression creation:
Option-01: implicit way -
var regExp = /[0-9]/;
Option-02: explicit way-
var regExp = new RegExp('[0-9]');
Note: better to use option-01 as option-02 has implication on execution speed.
Various patterns:
1. Direct match - /direct/. This pattern will find a match in string 'Looking for a direct match' but not in 'Misspelled the word diract'.
2. Special characters -
Pattern | Meaning/example | Matching String | Non matching string |
---|---|---|---|
\ | Escape character | ||
^ | matches beginning of input. /^A/ | Apple | Banana |
$ | matches end of input. /a$/ | Banana | apple |
* | matches preceding expression 0 or many times. /p*/ | - Apple - Orange | |
+ | matches preceding expression 1 or many times. /p+/ | - Apple - Peach | - Orange, any string not have p in it |
? | matches preceding expression 0 or 1 times. /p?/ | - Peach - Pear | - Apple - |
() | matches and remembers it. Also called capturing parentheses. /(p)/ | Table Cell | |
(?:) | Matches 'x' but does not remember the match | ||
(?=) | Look ahead. /A(?=p)/. Match only if A (capital) followed by p. | - Apple - Apricot | - Avocado - apple |
(?!) | negated look ahead. /A(?!p)/. Match only if A (capital) doesn't follow by p. | - Avocado - apple | - Apple - Apricot |
| | matches either one. /A|a/. | - Apple - apple | - one - Two - Three |
{} | matches exactly that many occurrences. /p{2}/. Has to be positive number. | - Apple - Pepper | - Apricot - Pear - Peach |
{ , } | matches at least first and at most second. /p{1,2}/. | - Apple - Pepper | - Apricot - Pear - Peach |
[] | Character set. /[Pe|pe]/. | - Pepper - Pear - Peach | - Apricot - Apple |
[^ ] | Negated character set. /[^pe]/. | - Pear - Peach - Apple - Apricot | - Pepper |
\b | matches word boundary where word character not preceded or followed wit any character. /\bp/. | - pear - peach | -Apple |
\d | matches digit character. /\d/. equals to /[0-9]/. | - 2apples - 3 Pears | - Apple - Pear |
\D | match non digit character. /\D/. equals to /[^0-9]/. | - Apple - Pear | - 2apples - 3 Pears |
\s | matches white space. /\s/. | - 2 Apples - Apple or orange | - AppleOrOrange - PearAndPeach |
\S | matches a single character other than white space. /\S/. | ||
\w | matches any alphanumeric words including _. /\w/. equals to /[A-Za-z0-9_]/. | - &^%$A match A | |
\W | Matches any non-word character. /\W/. equals to /[^A-Za-z0-9_]/. | - Appl# matches # | |
Note: the list is not complete. Check Resource links for complete list |
Regular Expression properties:
Property Name | Description |
---|---|
lastIndex | The index at which to start the next match |
ignoreCase | Indicates if the "i" flag was used to ignore case. Returns true or false |
global | Indicates if the "g" flag was used for global match. Returns true or false |
multiline | Indicates if the "m" flag was used match from multiple lines. Returns true or false |
source | Returns the pattern used in regular expression |
split | This method is in String. If match found, returns array of substrings. |
Methods related to regular expression:
Method Name | Description |
---|---|
exec | that executes a search for a match in a string. It returns an array |
re.exec(str) - matches the regular expression (re) against the input parameter string (str). Properties: [0] - The full string of characters matched [1], ...[n ] - matched substrings index - zero based, index of matched string input - the string match happening against | |
test | tests for a match in a string and returns true or false |
re.test(str) - regular expression (re), input parameter string (str). | |
match | This method is in String. Executes a search and returns an array of information or null on a mismatch |
str.match(re) - regular expression (re) pattern to match on string (str). | |
search | This method is in String. Returns the index if match found, else -1. |
str.search(re) - regular expression (re) pattern to search from string (str). | |
replace | This method is in String. Replaces matched substring with replacement substring. |
str.replace(re, newSubStr) - replace substring from string (str) if match found based on regular expression (re) pattern with new sub string (newSubStr). Note: a function can be used instead of newSubStr as replacement | |
split | This method is in String. If match found, returns array of substrings. |
str.split([separator[, limit]]) - Splits the string (str) based on separator. Limit value can be specified which is optional. If used, it splits on every match on separator but truncates the array to meet the limit. |
Regular expression with flags:
Syntax: /regular expression/flag;
Flags:
i - case ignore search
g - global search
m - multi line search
Examples:
1. Replace all instances of e or E in a String - /e|E/g.
2.
Resources:
1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
2.