Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda