Home > front end >  How can I "reverse" this regular expression?
How can I "reverse" this regular expression?

Time:12-16

In a piece of software where the teacher will be allowed to enter a regular expression intended to analyse the student's response to a question, I need to prevent the use of these 4 un-escaped characters:

. * ^ $

The following expression matches these un-escaped characters. How can I re-write it so that it does the reverse, i.e. so that it matches escaped characters but does not match unescaped ones? Of course, I can do this programmatically but I would prefer to do this directly in that software's authoring mode, where I'm allowed to enter just one regular expression. Here's the expression:

/(?<!\\)[\.\^\$\*\ \{\}]/g

Available at regex101

CodePudding user response:

You may use the following:

(?<!\\)(?:\\\\)*\\[.^$* {}]

This matches any of the characters inside the character class only if it's preceded by an odd number of backslash characters (i.e., a single backslash that is optionally preceded by other escaped ones).

Note: The .^$* {} characters don't need to be escaped as long as they're inside a character class.

Demo.

Breakdown:

  • (?<!\\) - Not preceded by a backslash character.
  • (?:\\\\)* - Zero or more pairs of backslash characters (i.e., an escaped backslash).
  • \\[.^$* {}] - An escaped character amongst .^$* {}.
  • Related