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
g
for "global" at the end to find every instance, like so:/
something/g
- Add
m
to "multi line" to the beginning/end of each line, not just the beginning/end of each string, like/
something/g
or/
something/gm
Character Classes
\s
White space
-
\s
is used in/\s/gm
to 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
-
\S
is used in/\S/gm
to 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
-
\d
is used in/\d/gm
to 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
-
\D
is used in/\D/gm
to 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
-
\w
is used in/\w/gm
to 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
-
\W
is used in/\W/gm
to 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)