js reg code example

Example 1: javascript regex

// \d	Any digit character
// \w	An alphanumeric character (“word character”)
// \s	Any whitespace character (space, tab, newline, and similar)
// \D	A character that is not a digit
// \W	A nonalphanumeric character
// \S	A nonwhitespace character
// .	Any character except for newline
// /abc/	A sequence of characters
// /[abc]/	Any character from a set of characters
// /[^abc]/	Any character not in a set of characters
// /[0-9]/	Any character in a range of characters
// /x+/	One or more occurrences of the pattern x
// /x+?/	One or more occurrences, nongreedy
// /x*/	Zero or more occurrences
// /x?/	Zero or one occurrence
// /x{2,4}/	Two to four occurrences
// /(abc)/	A group
// /a|b|c/	Any one of several patterns
// /\d/	Any digit character
// /\w/	An alphanumeric character (“word character”)
// /\s/	Any whitespace character
// /./	Any character except newlines
// /\b/	A word boundary
// /^/	Start of input
// /$/	End of input

Example 2: regular expression flags

Besides the regular expressions, flags can also be used to help developers with pattern matching.
/* matching a specific string */
regex = /sing/; // looks for the string between the forward slashes 9case-sensitive)… matches “sing”, “sing123”
regex = /sing/i; // looks for the string between the forward slashes (case-insensitive)... matches "sing", "SinNG", "123SinNG"
regex = /hello/g; // looks for multiple occurrences of string between the forward slashes...
/* groups */
regex = /it is (sizzling )?hot outside/; // matches "it is sizzling hot outside" and "it is hot outside"
regex = /it is (?:sizzling )?hot outside/; // same as above except it is a non-capturing group
regex = /do (dogs) like pizza 1/; // matches "do dogs like pizza dogs"
regex = /do (dogs) like (pizza)? do 2 1 like you?/; // matches "do dogs like pizza? do pizza dogs like you?"
/* look-ahead and look-behind */
regex = /d(?=r)/; // matches 'd' only if it is followed by 'r', but 'r' will not be part of the overall regex match
regex = / (?<=r)d /; // matches 'd' only if it is proceeded by an 'r', but 'r' will not be part of the overall regex match

Example 3: using regex in javascript

//Adding '/' around regex
var regex = /\s/g;
//or using RegExp
var regex = new RegExp("\s", "g");

Example 4: js regrex

var s = "Please yes\nmake my day!";
s.match(/yes.*day/);
// Returns null
s.match(/yes[^]*day/);
// Returns 'yes\nmake my day'