Sunteți pe pagina 1din 21

Regex Cheat Sheet

Emma Wedekind ✨ Feb 19 Updated on Feb 21, 2019 ・4 min read

#javascript

A regular expression, or 'regex', is used to match parts of a


string. Below is my cheat sheet for creating regular
expressions.

Testing a regex

Use the .test() method

let testString = "My test string";


let testRegex = /string/;
testRegex.test(testString);
Testing multiple patterns

Use the OR operator (|)

const regex = /yes|no|maybe/;

Ignoring case

Use the i flag for case insensitivity

const caseInsensitiveRegex = /ignore case/i;


const testString = 'We use the i flag to iGnOrE CasE';
caseInsensitiveRegex.test(testString); // true

Extracting the first match to a variable

Use the .match() function

const match = "Hello World!".match(/hello/i); // "Hello"

Extracting all of the matches in an array

Use the g flag

const testString = "Repeat repeat rePeAT";


const regexWithAllMatches = /Repeat/gi;
testString.match(regexWithAllMatches); // ["Repeat", "repeat", "rePeAT
Matching any character

Use the wildcard character . to be a placeholder for


any character

// To match "cat", "BAT", "fAT", "mat"


const regexWithWildcard = /.at/gi;
const testString = "cat BAT cupcake fAT mat dog";
const allMatchingWords = testString.match(regexWithWildcard); // ["cat

Matching a single character with multiple


possibilities

Use character classes, which allow you to define a


group of characters you wish to match
You place them inside square brackets []

// Match "cat" "fat" and "mat" but not "bat"


const regexWithCharClass = /[cfm]at/g;
const testString = "cat fat bat mat";
const allMatchingWords = testString.match(regexWithCharClass); // ["cat

Match letters of the alphabet

Use a range within the character set [a-z]

const regexWithCharRange = /[a-e]at/;


const catString = "cat";
const batString = "bat";
const fatString = "fat";

regexWithCharRange.test(catString); // true
regexWithCharRange.test(batString); // true
regexWithCharRange.test(fatString); // false

Match specific numbers and letters

You can also use the hyphen to match numbers

const regexWithLetterAndNumberRange = /[a-z0-9]/ig;


const testString = "Emma19382";
testString.match(regexWithLetterAndNumberRange) // true

Match a single, unknown character

To match a set of characters you don't want to have,


use the negated character set
To negate a character set, use a caret ^

const allCharsNotVowels = /[^aeiou]/gi;


const allCharsNotVowelsOrNumbers = /[^aeiou0-9]/gi;

Match characters that occur one or more times in a


row

Use the + symbol


const oneOrMoreAsRegex = /a+/gi;
const oneOrMoreSsRegex = /s+/gi;
const cityInFlorida = "Tallahassee";

cityInFlorida.match(oneOrMoreAsRegex); // ['a', 'a', 'a'];


cityInFlorida.match(oneOrMoreSsRegex); // ['ss'];

Matches characters that occur zero or more times in a


row

Use the asterisk *

const zeroOrMoreOsRegex = /hi*/gi;


const normalHi = "hi";
const happyHi = "hiiiiii";
const twoHis = "hiihii";
const bye = "bye";

normalHi.match(zeroOrMoreOsRegex); // ["hi"]
happyHi.match(zeroOrMoreOsRegex); // ["hiiiiii"]
twoHis.match(zeroOrMoreOsRegex); // ["hii", "hii"]
bye.match(zeroOrMoreOsRegex); // null

Lazy Matching

The smallest part of a string that matches the given


requirements
Regex, by default, are greedy (matches the longest
portion of a string meeting the given requirements)
Use the ? character to lazy match
const testString = "catastrophe";
const greedyRexex = /c[a-z]*t/gi;
const lazyRegex = /c[a-z]*?t/gi;

testString.match(greedyRexex); // ["catast"]
testString.match(lazyRegex); // ["cat"]

Match starting string patterns

To test for a match of characters at the beginning of a


string, use the caret ^ , but outside of the character set

const emmaAtFrontOfString = "Emma likes cats a lot.";


const emmaNotAtFrontOfString = "The cats Emma likes are fluffy.";
const startingStringRegex = /^Emma/;

startingStringRegex.test(emmaAtFrontOfString); // true
startingStringRegex.test(emmaNotAtFrontOfString); // false

Match ending string patterns

Use the dollar sign $ at the end of a regex to check


whether a pattern exists at the end of a string

const emmaAtBackOfString = "The cats do not like Emma";


const emmaNotAtBackOfString = "Emma loves the cats";
const startingStringRegex = /Emma$/;

startingStringRegex.test(emmaAtBackOfString); // true
startingStringRegex.test(emmaNotAtBackOfString); // false
Matching all letters and numbers

Use the \word shorthand

const longHand = /[A-Za-z0-9_]+/;


const shortHand = /\w+/;
const numbers = "42";
const myFavoriteColor = "magenta";

longHand.test(numbers); // true
shortHand.test(numbers); // true
longHand.test(myFavoriteColor); // true
shortHand.test(myFavoriteColor); // true

Match everything except letters & numbers

You can use for the opposite of \w with \W

const noAlphaNumericCharRegex = /\W/gi;


const weirdCharacters = "!_$!!";
const alphaNumericCharacters = "ab283AD";

noAlphaNumericCharRegex.test(weirdCharacters); // true
noAlphaNumericCharRegex.test(alphaNumericCharacters); // false

Match all numbers

You can use a character set [0-9] , or use the


shorthand \d
const digitsRegex = /\d/g;
const stringWithDigits = "My cat eats $20.00 worth of food a week.";

stringWithDigits.match(digitsRegex); // ["2", "0", "0", "0"]

Match all non-numbers

You can use the opposite of \d with \D

const nonDigitsRegex = /\D/g;


const stringWithLetters = "101 degrees";

stringWithLetters.match(nonDigitsRegex); // [" ", "d", "e", "g", "r",

Matching whitespace

Use \s to match white space and carriage returns

const sentenceWithWhitespace = "I like cats!"


var spaceRegex = /\s/g;
whiteSpace.match(sentenceWithWhitespace); // [" ", " "]

Matching non-whitespace

You can use the opposite of \s with \S

const sentenceWithWhitespace = "C a t"


const nonWhiteSpaceRegex = /\S/g;
sentenceWithWhitespace.match(nonWhiteSpaceRegex); // ["C", "a", "t"]
Matching character counts

You can specify a specific number of characters in a


row using {lowerBound, upperBound}

const regularHi = "hi";


const mediocreHi = "hiii";
const superExcitedHey = "heeeeyyyyy!!!";
const excitedRegex = /hi{1,4}/;

excitedRegex.test(regularHi); // true
excitedRegex.test(mediocreHi); // true
excitedRegex.test(superExcitedHey); //false

Matching lowest number of character counts

You can define only a minimum number of character


requirements with {lowerBound,}
This is called a quantity specifier

const regularHi = "hi";


const mediocreHi = "hiii";
const superExcitedHey = "heeeeyyyyy!!!";
const excitedRegex = /hi{2,}/;

excitedRegex.test(regularHi); // false
excitedRegex.test(mediocreHi); // true
excitedRegex.test(superExcitedHey); //false

Matching an exact number of character counts


You can specify the exact number of character
requirements with {requiredCount}

const regularHi = "hi";


const bestHi = "hii";
const mediocreHi = "hiii";
const excitedRegex = /hi{2}/;

excitedRegex.test(regularHi); // false
excitedRegex.test(bestHi); // true
excitedRegex.test(mediocreHi); //false

Matching all or none of a character

To check whether a character exists, use the ?

const britishSpelling = "colour";


const americanSpelling = "Color";
const languageRegex = /colou?r/i;

languageRegex.test(britishSpelling); // true
languageRegex.test(americanSpelling); // true

Sore eyes?
dev.to now has dark mode.

Select night theme in the


"misc" section of your
settings

Emma Wedekind ✨
UX Engineer, bibliophile, & cat mom
+ FOLLOW

@emmawedekind EmmaWedekind emmawedekind www.emmawedekind.com

Add to the discussion

PREVIEW SUBMIT

Feb 19
Brian Kichler

I go cross-eyed dealing wit h regex, but t his is an excellent reference I'm definit ely coming back to.
I almost always head to regex101.com whenever pat t ern-mat ching st art s to devour my brain.

30 REPLY

 
Feb 20
Richard vK

Just shared t he link to regex101 wit h my colleagues today - great tool!

4 REPLY

 
Feb 20
Saúl Blanco Tejero

RT

1 REPLY
  Feb 19
Alex Lohr

Using t he | operator is a dangerous habit . You easily forget to guard yourself against mat ching
subst rings, for example consider t he following line:

const isLocalHost = /127.0.0.1|localhost/.test(location.host);

And now what happens on localhost.mydevious.url ? The secure solut ion is to use ^ and $ to
gat e t he st art and end of t he t est ed st ring.

Also, one t rick up JS regex's sleeve is t he back reference ( \1-\9 ):

/(["'])(.*?)\1/.test('"I can match Emma\'s full strings"') && RegExp.$2;


/(["'])(.*?)\1/.test("'I can match when Emma say \"things in strings\"'") && RegExp.$2;

This will re-use t he (matches) inside t he same regex.

15 REPLY

 
Feb 25
Chris Watson

The real guard is to writ e t est s to assert t he correct behaviour :)

3 REPLY

 
Feb 26
Alex Lohr

Just don't forget about t hose edge cases ;-)

4 REPLY

Feb 19
Nick Taylor

Todd Mot to™


@toddmot to
Just remember, Elon Musk doesn’t know RegExp eit her.
19:45 PM - 19 Feb 2019
29 175

14 REPLY

Feb 19
Miloslav Voloskov

For me, Regex and Perl are write-only languages. I can't debug, edit or even read regex – I just
rewrit e it from scrat ch wit h some tool like RegExr or somet hing. For me, a person who can
memorise all t hat synt ax is definit ely a superhuman.

8 REPLY

 
Feb 19
Denys Séguret

Making code readable is half t he job of t he coder. It 's also t rue for regexes, which means you
have to look for ways to separat e part s and comment your regexes (or at least name t he
groups).

Fort unat ely, you can find solut ions in most languages. Here are t wo examples from some of my
OS codes:

In Javascript :

cmdArgRegex = miaou.lib("rex")`
([a-z ]*) // options (optional)
(-?\d*\s*d\s*[\d+-]+) // left rolldef (mandatory)
(?: // inequation (optional)
\s*
([<>=]+) // operator
\s*
([\w+-]+) // right rolldef or scalar
)?
\s*$
/i`;

(I t hink t here are JS libs to do t hat wit hout t aking my code, now)

In rust :
static ref RE: Regex = Regex::new(
r"(?x)
^
(?P<slash_before>/)?
(?P<pattern>[^\s/:]+)?
(?:/(?P<regex_flags>\w*))?
(?:[\s:]+(?P<verb>\S*))?
$
"

(t his is t he st andard way in t his language)

12 REPLY

Feb 21
Sebastijan Grabar

The funny t hing about t hese Regex cheat cheet s is no mat t er how many of t hem I put in my
bookmarks, I never end up using t hem.

8 REPLY

 
Feb 26
Precious adeyinka

sebast ian 😂 me too


2 REPLY

Feb 19
George W Langham

I t end to not bot her learning regex, t he cases where it 's useful, I'll just go to a sit e like regexr.com
and t hen use t heir tools to build one.

6 REPLY

 
Feb 20
Jackson Elfers

In t hink t hat 's t he general consensus. I only use it occasionally so it 's not wort h my t ime to be
100 percent fluent .

3 REPLY
  Feb 20
Luis M Alvarez Pacheco

Anot her cheat sheet for my privat e gist collect ion lol

5 REPLY

Feb 26
mtomasek2

I'm using regex debuger, regexbuddy.com/, to debug different regex flavors. It saved me a lot of
t ime over t he years. It can also run on linux (using Wine).
They also have a tool for building regexps, regexmagic.com/, but I'm not using is so I'm just saying
it is out t here.

3 REPLY

Feb 25
Leonardo Galante

Great cheat sheet , t hank you Emma! Soon I'm gonna make a post about t his ext ension I made for
VSCode t hat could help underst anding RegExp: market place.visualst udio.com/it ems...

3 REPLY

Feb 26
Phillip Dodd

Oh my, I wish t hat I had encount ered t his post about t wo mont hs ago before I began t he difficult
journey of acquiring what (lit t le) regex knowledge I have now... haha!

I'm absolut ely going to be bookmarking t his to revisit next t ime I have t he need and will be sharing
it wit h my t eam. You've laid t his out in a very underst andable way; t hanks for sharing :)

3 REPLY

Thomas Junk ツ Feb 20

For t he day-to_day development , I recommend using Rubular or Regexly

5 REPLY
  Apr 30
Guillaume Duchemin

Thx a lot for t his awesome cheat sheet !


You made a mist ake in t his case

const regexWithLetterAndNumberRange = /[a-z0-9]/ig;


const testString = "Emma19382";
testString.match(regexWithLetterAndNumberRange) // true

The result of mat ch is // ["E", "m", "m", "a", "1", "9", "3", "8", "2"] ;)

3 REPLY

Feb 20
I'mAHopelessDev

very neat , t hanks!

4 REPLY

Feb 20
plainJavaScript

Pret t y fine.

4 REPLY

Feb 19
Mehdi Vasigh

Great post and doubles as a great pract ice assessment if you hide all of t he code blocks!

4 REPLY

Feb 20
Bartosz Maciejewicz

I <3 it :) t hank you very much :)


4 REPLY

Feb 19
Sohail Nasir

Thanks, t his makes regex less scary! Keep up t he good work

4 REPLY

Jun 20
Phil Ashby

Nicely done :)

Always choose carefully when choosing to use a regular expression of course. Our primary
applicat ion at work is for input validat ion, drawing heavily on t he excellent work done in OWASP:
owasp.org/index.php/OWASP_ Validat i...

1 REPLY

Feb 25
mmeyers00

Shouldn't t his also go under #regex?

3 REPLY

Feb 23
Lundeee

Never ever did i wrot e single regex wit hout some kind of cheat sheet or tool. Thank you.

3 REPLY

Feb 20
Saúl Blanco Tejero

I love regexp 😊
3 REPLY
  Feb 19
monsterooo


3 REPLY

Feb 25
10secondsofcode

Nicely explained....!

2 REPLY

Feb 27
LuisPa García

Great post Emma!

2 REPLY

Feb 20
Jackson Elfers

There are definit ely some regex wizards out t here, great work put t ing t his toget her. 😁
2 REPLY

Feb 25
Shah Nawaz Shuvo

This is a great reference guide. Thank you Emma

2 REPLY

Feb 22
Jon Randy

Best regex cheat sheet I ever came across - applet ree.or.kr/quick_ reference_ ca...

2 REPLY
  Feb 21
Vinicius Dutra

t hanks for share t his useful t ips

2 REPLY

Feb 26
Tutlane

Thanks emma for t he list , will share it in our JavaScript topics.

2 REPLY

Feb 25
UniWrighte

I've most ly used .t est , but you make good use of t he .mat ch met hod. Thanks for t he great regex
post wit h a JavaScript focus!

2 REPLY

VIEW FULL DISCUSSION (49 COMMENTS)

code of conduct - report abuse

Classic DEV Post from Jun 17

How to Get Smarter Without Knowing Anything


Ryland G

Extend your brainpower with the internet


377 27

From one of our Community Sponsors


What software technologies will earn you the
highest pay?
Fahim ul Haq

Helping you choose the right languages and skills to maximize your value
563 33

Another Post You Might Like

Async Form Posts With a Couple Lines of Vanilla


JavaScript
Rik Schennink

How to improve UX and transform a classic synchronous form post into an


asynchronous one with a couple lines of JavaScript
65 5

Another Post You Might Like

JavaScript One-Liners That Make Me Excited


Andrew Healey

A collection of smart and zany solutions to some common, and quite uncommon,
problems.
760 47
How to use `import/export` in Node without Babel
Corey Cleary - Oct 21

13 useful JavaScript array tips and tricks you should know


Duomly - Oct 21

Modern React interview questions for junior developers (pt. 2)


Matt Upham - Oct 21

Building a modal module for React with React-Router


Brian Neville-O'Neill - Oct 21

Home About Privacy Policy Terms of Use Contact Code of Conduct

DEV Community copyright 2016 - 2019  🔥

S-ar putea să vă placă și