Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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 '

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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 '
about 4 years ago · Juan Pablo Isaza Report

0

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>'));
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!