Regex to match character unless it is preceded by an odd number of another specific character

Viewed 204

Another way to state my problem is to match a character always when it is preceded by an even number (0, 2, 4, ...) of another specific character.

In my case I want to match all ' characters in string unless it is preceded by an odd number (1, 3, 5 ...) of ?

example:

- ?' => shouldn't match (preceded by one ?)
- ??' => Should match (preceded by 2 ?)
- ?????' => Shouldn't match (preceded by 5 ?)

Lets consider this scenario:

We have this string : ' ??' ????' ?' ??????' then the regex should match all ' characters in this case except for the 4th one, so for example if I want to use String.split(regex) the result would be ['', '??', '????', ?' '??????']

Currently I was using this regex: (?<!\?)', but the problem is that it matches only if there is no ? before '

2 Answers

You may use this regex with a lookbehind condition:

(?<=([^?]|^)(?:\?\?)*)'

RegEx Demo

RegEx Explanation

  • (?<=: Start lookbehind condition
    • ([^?]|^): Match a non-? character or start
    • (?:\?\?)*: Match 0 or more pairs of ?
  • ): End lookbehind condition
  • ': Match a '

You can use

/(?<=(?<!\?)(?:\?\?)*)'/g

See the regex demo. Details:

  • (?<=(?<!\?)(?:\?\?)*) - a positive lookbehind that matches a location that is preceded with any zero or more occurrences of double ? not immediately preceded with another ?
  • ' - a ' char.

Sample code:

const texts = ["The ?' should not match","The ??' should match","?????' => The ?????' should not match"];
const rx = /(?<=(?<!\?)(?:\?\?)*)'/g
for (var text of texts) {
  console.log(text, '=>', rx.test(text));
}

If you need replacing, it is possible with

const texts = ["The ?' should not match","The ??' should match","?????' => The ?????' should not match"];
const rx = /(?<=(?<!\?)(?:\?\?)*)'/g
for (var text of texts) {
  console.log(text, '=>', text.replace(rx, '<MATCH>$&</MATCH>'));
}

Related