Intro
I was recently doing a code challenge for a job interview that required me to strip out all nonalphabetic characters. "Ah! I should use Regular Expressions for this!" I thought in triumph, impressed that I even knew what regular expressions were. That fleeting moment of glory faded once I decided to brush up on regular expressions and landed on the encouragingly-named Regular Expressions Cheatsheet. I had no idea how to use it!
So, for people like me, here is a Cheatsheet for the Regular Expressions Cheatsheet, Part 2: Character Classes
What are Character Classes?
A character class is a special notation that matches any symbol from a certain set.
Anatomy of a regular expression
- Forward slashes go on either end like so:
/something/ - Add
gfor "global" at the end to find every instance, like so:/something/g - Add
mto "multi line" to the beginning/end of each line, not just the beginning/end of each string, like/something/gor/something/gm
Character Classes
\s White space
-
\sis used in/\s/gmto find the following]: The lion roared - Example on regex101.com
- Example in Javascript:
let sentence = "The lion roared";
let regex = /\s/gm;
let found = sentence.match(regex);
console.log(found); // [ ' ', ' ' ]
\S Not white space
-
\Sis used in/\S/gmto find the following]: The lion roared - Example on regex101.com
- Example in Javascript:
let sentence = "The lion roared";
let regex = /\S/gm;
let found = sentence.match(regex);
console.log(found); //
[ 'T', 'h', 'e', 'l',
'i', 'o', 'n', 'r',
'o', 'a', 'r', 'e',
'd']
\d Digit
-
\dis used in/\d/gmto find the following]: The 3 lions roared - Example on regex101.com
- Example in Javascript:
let sentence = "The 3 lions roared";
let regex = /\d/gm;
let found = sentence.match(regex);
console.log(found); // [ '3' ]
\D Not digit
-
\Dis used in/\D/gmto find the following]: The 3 lions roared - Example on regex101.com
- Example in Javascript:
let sentence = "The 3 lions roared";
let regex = /\D/gm;
let found = sentence.match(regex);
console.log(found); //
[
'T', 'h', 'e', ' ', ' ',
'l', 'i', 'o', 'n', 's',
' ', 'r', 'o', 'a', 'r',
'e', 'd'
]
\w Word
-
\wis used in/\w/gmto find the following]: The lion roared - Example on regex101.com
- Example in Javascript:
let sentence = "The lion roared";
let regex = /\w/gm;
let found = sentence.match(regex);
console.log(found); // [
'T', 'h', 'e', 'l',
'i', 'o', 'n', 'r',
'o', 'a', 'r', 'e',
'd'
]
\W Not word
-
\Wis used in/\W/gmto find the following]: The lion roared - Example on regex101.com
- Example in Javascript:
let sentence = "The lion roared";
let regex = /\W/gm;
let found = sentence.match(regex);
console.log(found); // [ ' ', ' ' ]
Dunce Corner
I can't make any of the following work. Try them out and report back in the comments:

Top comments (0)