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 IV: Assertions
What's an Assertion?
We use assertions when we want to assert a specific sequence and set of conditions for a match. It's really better explained with examples, so read on!
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
Assertions
?=
Lookahead assertion
-
?=
is used in/lion (?=roared)/
to find the following: The lion roared - Example on regex101.com
- Example in Javascript:
let sentence = "The lion roared";
let regex = /lion (?=roared)/;
let found = sentence.match(regex);
console.log(found); // [ 'lion ', index: 4, input: 'The lion roared', groups: undefined ]
?!
Negative lookahead
-
?!
is used in/lion (?!yawned)/
to find the following: The lion roared - Example on regex101.com
- Example in Javascript:
let sentence = "The lion roared";
let regex = /lion (?!yawned)/;
let found = sentence.match(regex);
console.log(found); // [ 'lion ', index: 4, input: 'The lion roared', groups: undefined ]
?<=
Lookbehind assertion
-
?<=
is used in/(?<=lion) roared/
to find the following: The lion roared - Example on regex101.com
- Example in Javascript:
let sentence = "The lion roared";
let regex = /(?<=lion) roared/;
let found = sentence.match(regex);
console.log(found); // [ ' roared', index: 8, input: 'The lion roared', groups: undefined ]
?<!
Negative lookbehind
-
?<!
is used in/(?<!asparagus) roared/
to find the following: The lion roared - Example on regex101.com
- Example in Javascript:
let sentence = "The lion roared";
let regex = /(?<!asparagus) roared/;
let found = sentence.match(regex);
console.log(found); // [ ' roared', index: 8, input: 'The lion roared', groups: undefined ]
Top comments (0)