code

Regular Expressions Cheat Sheet

OperatorCodeExample
Or|/yes|no/
let testStr = "Pumpkin";
let testRegex = /P(engu|umpk)in/; testRegex.test(testStr);
Ignore Casei/Matt/i
Extract Multiple Instancesg/Repeat/g
Wildcard (one character)./hu./
Character Classes[ ]/b[aiu]g/
Range[-]/[a-e]at/
/[a-z0-9]/
Avoid Match[^]/[^aeiou]/
One or More Matches+/a+/
Zero or More Matches*/go*/
Lazy Match (smallest result)?/<.*?>/
Beginning of String^/^Ricky/
Ending of String$/story$/
Match All Numbers/Letters/Underscore\w/\w+/
/[A-Za-z0-9_]+/
~Match All Numbers/Letters/Underscore\W
Match All Numbers\d
Match All Non-Numbers\D
Match Whitespace\s
Match Non-Whitespace\S
Specify Number of Matches{#,#}a{2,3}h
a{2,}h
a{2}h
Optional Match?/colou?r/
Positive Lookahead(?=...)let quRegex = /q(?=u)/;
Negative Lookahead(?!...)let qRegex = /q(?!u)/;
Capture Group\1let repeatStr = "regex regex";
let repeatRegex = /(\w+)\s\1/; repeatRegex.test(repeatStr); repeatStr.match(repeatRegex);
Search/Replace.replacelet wrongText = "The sky is silver.";
let silverRegex = /silver/; wrongText.replace(silverRegex, "blue");

Leave a Reply

Matt is the author of five Apress books including Learn RStudio IDE, Quick, Effective, and Productive Data Science, Objective-C Recipes, Swift Quick Syntax Reference, Objective-C Quick Reference, and the upcoming Pro Data Visualization with R and JavaScript. He has over 20 years of experience in technology, psychometrics, and data analytics working in major higher education institutions such as The College Board and Educational Testing Service. He has earned a Master’s degree in Information Systems Management and a Bachelor’s degree in Quantitative Psychology.