Skip to content

Instantly share code, notes, and snippets.

@nozzlegear
Last active May 30, 2016 00:26
Show Gist options
  • Select an option

  • Save nozzlegear/acc0dcb6570898d8ab2cc7530fef46ed to your computer and use it in GitHub Desktop.

Select an option

Save nozzlegear/acc0dcb6570898d8ab2cc7530fef46ed to your computer and use it in GitHub Desktop.
Regex basics
// [0] the entire string, "require('my-module')"
// [1] require('
// [2] my-module
// [3] ')
const captures = /(require\s*\(["'])(.*)(["']\s*\))/ig.exec(replacement);
const requireStart = captures[1];
const requireEnd = captures[3];
let moduleName = captures[2];
// Use parentheses to denote capture groups, e.g. /(require)/ig will capture the word "require".
// Escape special characters with a backslash, e.g. /\(require\)/ig will find "(require)".
// All regexes start and end with a forward slash. After ending the regex, add flags such as 'i' for case-insensitive searches and 'g' for global searches. Flags can be combined.
// Search for a single whitespace with \s. Match multiple whitespaces with \s+. Match multiple whitespaces or no whitespaces with \s*.
// Add wildcards with a period. Add infinite wildcards with .+. Add infinite or no wildcards with .*.
// Add 'or' expressions with brackets, e.g. ["'] will find one " or ' character.
// Let the last expression be optional with ?, e.g. ["']? will look for optional quote characters but won't stop the regex if it doesn't find them.
// Experiment with regexes at http://www.regexr.com/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment