Regex to match backslash unless followed by _, %, ' or an odd number of backslashes

I’m trying to write a regex expression to select a backslash.

The problem is that I only want to select it if it’s not followed by an odd number of backslashes, or one of the characters in this set: [_%’]. I don’t mind which backslash in the sequence is selected, first or last, I just need to select exactly one in the sequence (or each first/last in each sequence – there can be more in a single string).

Example nothing selected:

this is \\ my string
this is my string\\\\
this is my \\\\\\ string
this is \' my string
this is \_ my string
this \% is my string
this \'\_\\\% is my string
this is\\my string
this is my\\\_string

Example select first backslash (or last)

this is \ my string
this is \\\ my string
this is \\\\\ my string
this is\\\my string

In next example, two backslashes in total should be selected, the single one from the first block, and the first/last of the three backslashes in sequence:

this is \ my \\\ string 

I semi did do it with expression (?<!\\)\\(?!([_%'])), except I don’t know how to add the condition that it’s not followed by an odd number of backslashes that would work with this.

>Solution :

Your attempt indeed only needs the additional logic for ensuring the odd number of backslashes.

So you could match the first backslash as follows:

  • Assert that it is the first (there is no immediately preceding backslash) — you already had this
  • Assert that the number of backslashes after the match is even and not followed by any of the special characters, nor another backslash.

Regex:

(?<!\\)\\(?=(?:\\\\)*(?![\\'_%]))

Leave a Reply