DEV Community


Regular Expressions cheat sheet

Rae Liu
I like to share ideas and snippets!
・2 min read

Regular expression is a powerful tool, and it can save lots of lines codes sometimes.

What is Regex

Regex(Regular Expression) describes a pattern of a certain amount of text, so it can be used for string editing.

Online tool

Not sure if your Regex works? Try Regex101, it can make your Regexes much easier.
I also recommend Regular Expression Info, it explains all details that you need to know.

Cheat Sheet

Character Meaning Example
^ the beginning of the string
$ the end of the string
\b whole word only \babc\b matches 'abc', but not 'abcc '
\B if the pattern is fully surrounded by word \Babc\B mathes 'aabcc', but not 'abc'
. anything
\d single digit in 0-9
\D single non-digit
\w single word character
\W single non-word
\s white space(space, tab, return, new line)
\S non-whitespace
\t tab
\r return
\n new line
\g global search, which means it doesn't stop at the first match
* zero or more of the previous abc* matches a string that has ab followed by zero or more c
+ one or more of the previous abc+ matches a string that has ab followed by one or more c
? zero or one of the previous abc? matches a string that has ab followed by zero or one c
?: non-capturing group
X{m} number of X === m
X{m,} m < number of X
X{m, n} m < number of X < n
(X | Y) X or Y
[...] any of characters in the class [abcd] matches a string that has one of the char (a, b, c, d)
- range [a-d] same as above

Key words from the cheat sheet

Anchor is not a pattern, it is a position.
It matches a position before, after or between characters.
For example, ^ is the beginning of the string, and it is also a start of line anchor.

\b is a word boundary because \babc\b has to match the whole word abc.
\B is non-word-boundary because \Babc\B means any words that includes abc (abcc, eabc).

Greedy: The optional item is included in the match if possible. ? is a typical example of greedy quantifiers. abc? can match either abc or ab.
Lazy: The optional item is excluded in the match if possible. ?? is a typical one because abc?? only matches ab.
Here is the best example from stack overflow -

Non-capturing group
?: means the pattern doesn't capture to the group. It usually uses with .match(). So if you use ?:, then the pattern won't be included to the array.
Example from stack overflow -

Hope this post helps ❤️

Discussion (2)

pradeepradyumna profile image
Pradeep Pradyumna

Thanks for sharing this article. Just wanted to share that if at all someone is looking for readymade patterns, I have found very much useful. It has a section called "Community Patterns" where one can avail of tons of ready-made patterns and customize if required. 😀

maulik profile image

Thank you for the post.
I use regex a lot in my work. It's very helpful and once you start understanding and using it, it becomes more clear. many developers are afraid of regex but please don't be.