Collect some RegExp concepts and demos from MDN.
(Some of these demos modified by myself).
RegExp As Object
1 | var re = new RegExp("Shelley\s+Powers"); |
RegExp methods
test: quickly and simple
Returns true or false
1 | var demo = 'abc rayjune'; |
If the regex has the global flag set, test() will advance the lastIndex of the regex.
1 | var regex = /foo/g; |
exec: overall but complicated
The exec() method executes a search for a match in a specified string. Returns a result array, or null.
1 | var str = 'hello -rayjune'; |
once use ‘\g’
1 | var reg = /hello/g; |
and the re has lastIndex property
1 | var myRe = /ab*/g; |
String method
search: just index
The index of the first match between the regular expression and the given string;
if not found, -1.
1 | var str = "hey JudE"; |
match: return eligible array
An Array containing the entire match result and any parentheses-captured matched results;
null if there were no matches.
1 | var str = 'hello -rayjune'; |
once use ‘\g’
1 | var reg = /hello/g; |
replace: (regexp|substr, newSubStr|function)
1 | var a = 'abc de'; |
Switching words in a string
1 | var re = /(\w+)\s(\w+)/; |
split: simple
1 | var re = /like/; |
Special characters
\s
1 | var re = /Shelley\s+Powers/; |
. (The decimal point)
matches any single character except the newline character.
1 | var re = /.n/; |
not match na
(x)
Matches ‘x’ and remembers the match, as the following example shows. The parentheses are called capturing parentheses.
1 | var re = /(a)(b)/; |
(?:x)
Matches ‘x’ but does not remember the match.
1 | var re = /(?:a)(?:b)/; |
And let you define subexpressions for regular expression operators to work with.
1 | var re1 = /foo{1,2}/; |
x(?!y)
Matches ‘x’ only if ‘x’ is not followed by ‘y’
1 | var re = /ray(?!june)/; |
[xyz]
This pattern type matches any one of the characters in the brackets, including escape sequences.
1 | console.log(/[\/]/.test('/')); // true |
[^xyz]
It matches anything that is not enclosed in the brackets
1 | console.log('abcdef'.match(/[^a-c]/g)); // (3) ["d", "e", "f"] |
\b
Matches a word boundary.
1 | console.log('moon'.match(/\bm/)); // ["m", index: 0, input: "moon"] |
\B
Matches a non-word boundary.
1 | console.log('possibly yesterday.'.match(/y\B./)); // ["ye", index: 9, input: "possibly yesterday."] |
\d
Matches a digit character. Equivalent to [0-9].
\D
Matches a non-digit character. Equivalent to [^0-9].
\r
Matches a carriage return
\s
Matches a single white space character, including space, tab, form feed, line feed.
\w
Matches any alphanumeric character including the underscore. Equivalent to [A-Za-z0-9_]
1 | console.log('ray_june'.match(/\w/g)); (8) ["r", "a", "y", "_", "j", "u", "n", "e"] |
\W
Matches any non-word character. Equivalent to [^A-Za-z0-9_].