How to Match Escaped and Non-Escaped Characters with Regex

Rabah TaibRabah Taib
2 min read
💡
We'll use (@) as the target character in these examples.

Match a non-escaped character

Final result

const regexp = /(?<=(?<!\\)(?:\\{2})*)@/

Though process

First, let's start with the most common solution: a regular expression that matches (@) not preceded by an escape character.

const regexp = /(?<!\\)@/

The problem with this regexp is that it only checks the first character to the left:

To fix that, we need to ensure that (@) is preceded by zero or more pairs of escape characters:

const regexp = /(?<=(?:\\{2})*)@/

We still have one last problem: (@) being preceded by an odd number of escapes also means it's preceded by an even number of escapes. This means the regexp will succeed with any number of escapes:

To fix this once and for all, we need to make sure the regexp only succeed if the even number of escapes are not followed by another escape:

const regexp = /(?<=(?<!\\)(?:\\{2})*)@/

Match an escaped character

Final result

const regexp = /(?<=(?<=(?<!\\)(?:\\{2})*)\\)@/

Thought process

To match an escaped character, we need to adjust the regexp so it matches (@) that is preceded by an escape, and that escape must be preceded by an even number of escapes, making the total an odd number of escapes.

0
Subscribe to my newsletter

Read articles from Rabah Taib directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rabah Taib
Rabah Taib