Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda