Skip to content

Instantly share code, notes, and snippets.

@ButlerFuqua
Last active February 11, 2019 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ButlerFuqua/4994a22cc88c2beb437c6b9052449f79 to your computer and use it in GitHub Desktop.
Save ButlerFuqua/4994a22cc88c2beb437c6b9052449f79 to your computer and use it in GitHub Desktop.
Reference of some common regular expression meta characters
let re;
// Literal Characters
re = /hello/;
re = /hello/i;
// Metacharacter Symbols
re = /^h/i; // Must start with
re = /world$/i; // Must end with
re = /^hello$/i; // Must begin and end with
re = /h.llo/i; // Can match any one character - .
re = /h*llo/i; // Can match any character 0 or more times - *
re = /gre?a?y/i; // optional character
re = /gray\?/i; // Escape character
// Brackets [] - Character Sets
re = /gr[ae]y/i; // Must be an a or e
re = /[GF]ray/; // Must be a G or F
re = /[^GF]ray/; // Match anything except a G or F
re = /^[GF]ray/; // Match start with G or F
re = /[A-Z]ray/; // Match any uppercase letter
re = /[a-z]ray/; // Match any lowercase letter
re = /[A-Za-z]ray/; // Match any letter
re = /[0-9]ray/i; // Match any digit
// Braces {} - Quantifiers
re = /Hel{2}o/i; // Must occur exactly {m} amount of times, letter before
re = /Hel{2,4}o/i; // Must occur between {m,m) times}
re = /Hel{2,}/i; // Must occur at least {m} times
// Parentheses () - Grouping
re = /([0-9]x){3}/; // Matches 3x three times = '3x3x3x'
re = /^([0-9]x){3}$/; // Must begin and end, so exaclty 3x3x3x
// Shorthand Character Classes
re = /\w/; // Word chracter = alphanumeric or _
re = /\w+/; // + equals one or more
re = /\W/; // Non-Word characters. Non alphanumeric or _
re = /\d/; // Match any digit
re = /\d+/; // Match any digit one or more times
re = /\D/; // Non-digit
re = /\s/; // Match white space char
re = /\S/; // Match non-white space char
re = /Heaven\b/; // Word boundary
// Assertions
re = /x(?=y)/; // Match x only if followed by y
re = /x(?!y)/; // Match x only if not followed by y
// String to match
const str = `Heaven xy`;
// Log Results
const result = re.exec(str);
console.log(result);
function reTest(re, str) {
if (re.test(str)) {
console.log(`${str} matches ${re.source}`)
} else {
console.log(`${str} does not match ${re.source}`);
}
}
reTest(re, str);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment