Regular Expressions Reference

Reference

This post is being added retrospectively in order to consolidate all of my learning info in one searchable place. Comments are new (May 2022) but the code is old…use at your own risk!

Here are the notes I took in a workshop where we learned about regular expressions aka regex.

The basic construct of a regular expression is:

\pattern\flag

Common Flags:

\i = case insensitive
\g = general - will find all patterns (not just first)
/m = multi-line
\s = any character that’s a space
\S = any character that’s not a space
\^ = beginning of a string
[^d] = any character in a set that is NOT d
\$ = end of a string
[a-z] = any character a to z
. = any characters (except in brackets, when it just means itself)
\. = literally a period
\d - any numerical character
\D = any NON-numerical character, equivalents to [^0-9]
{n} = matches number of times
\b = word boundary ==> \b\w+\b matches EVERY word without punctuation
\B = any sections that’s NOT a word boundary
* = matches any number of patterns to infinity

  • Flags can be in any order, best practice is to list them alphabetically
  • Creating a set inside a pattern - match any of the characters, i.e. /pipp[aeiou]/gi would match pippa, Pippe, pippo, etc..

Creating a RegEx in JavaScript:

variable method: var myRegex = /abc/g;
class method: var myRegEx = new RegExp('abc','g');

RegExp Methods:
myRegEx.exec(string)
myRegEx.test(string)

String Methods:
myRegEx.match(str);
myRegEx.replace(str);
myRegEx.split(str);
myRegEx.search(str);