Guide for Regex
Lesson 1: Positive & Negative Lookahead & Lookbehinds
Lookaheads
& Lookbehinds
allow you to match for patterns found ahead/behind some given argument.
When wanting to extract B, which comes after A, without also extracting A, lookaheads
/lookbehinds
combined with match
are super helpful.
lookahead
& lookbehinds
are both divided into 2 types: positive & negative.
- Type 1: Positive Look Ahead
General form:
/.+(?=AAA)/
Description
Positive Lookaheads
allow you to match for patterns that are found (exist) ahead of some given argument.
- Use Case: When wanting to extract B, which comes after A, without also extracting A,
lookaheads
combined withmatch
are super helpful.
Examples
Example 1: grab just the name of a file ending with .d.ts extension
const exampleString = 'config.d.ts';
const positiveLookaheadRegex = /.+(?=\.d\.ts)/g;
positiveLookaheadRegex.test(exampleString); // returns true
exampleString.match(positiveLookaheadRegex); // returns 'config' (without '.d.ts' !!!)
Example 2: grab the first char that comes right before the letter A
exampleString = 'cat123A-catzzzA';
regex = /.(?=A)/g;
exampleString.match(regex);
Example 3: password must include at least 5 characters, and at least 2 consecutive digits.
const myRegex = /(?=\w{5})(?=\D*\d{2})/g;