Skip to content

Instantly share code, notes, and snippets.

@mroffice
Last active February 15, 2016 13:23
Show Gist options
  • Save mroffice/40525a4664a93ba936fb to your computer and use it in GitHub Desktop.
Save mroffice/40525a4664a93ba936fb to your computer and use it in GitHub Desktop.
An overview of Regular Expressions, with examples

Flags

Flag Description Truthy Example Falsey Example
^ Matches the beginning of input /^b/.test("bananas") /^ananas/.test("bananas")
\ In effect reverses the 'specialness' of a letter /\bb/.test("bananas") /b\b/.test("bananas")
$ Matches the end of input /anas$/.test("bananas") /banan$/.test("bananas")
* Matches the preceeding expression 0 or more times /bananas*/.test("banana") or /bananas*/.test("bananasssssssss") /(bananas)*/.test("monkey")
+ Matches the preceeding expression 1 or more times /bananas+/.test("bananasss") /bananas+/.test("banana")
? Matches the preceeding character 0 or 1 time /ba?na?na?/.exec("banana") // => ["banana"] or /ba?na?na?/.exec("bnn") // => ["bnn"] /ba?na?na?/.exec("bana") // => null
. Matches any character except newline /monkey./.test("monkeys") // => true /monkey./.test("monkey") // => false
(x) Capturing parenthesis: remembers the match for use in future, in a replace for example
{n} Matches exactly n occurrences of the preceeding expression /monke{3}/.exec("monkeeeees") // => ["monkeee"] /moon {1}keys/.test("moonkeys")
{n,m} Matches at least n and at most m occurrences of the preceeding expression /che{1,2}se/.test("cheese") /che{3,5}se/.test("cheese")
[abc] Character set. Matches any one of the characters
[^abc] Negates the above
\b Matches word boundaries
\B Matches non-word boundaries
\d Matches a digit character
\D Matches a non-digit character
\r Matches a carriage return
\s Matches any white space character
\S Matches any non-white space character
\t Matches a tab
\w Matches any alphanumeric character, or underscore
\W Matches any non-alphanumeric character, or underscore

Analytics

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment