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

143
Visualizações
How to capture one particular instance of a string only if it occurs twice in regex?

I have a regex expression: /diff\\left\((...*?\\right\){0,1})\\right\)/gm and the string I want to match is diff\left(5x^2\right) + diff\left(5x^2+\tan\left(x\right)\right).

I want to match in such a way that there are two matches diff\left(5x^2+\right) and diff\left(5x^2+\tan\left(x\right)\right) each having captured groups 5x^2 and 5x^2+\tan\left(x\right). I want to add \right) inside a captured group once only if it occurs twice. However, I'm only getting a single match with the entire 5x^2\right)+diff\left(5x^2+\tan\left(x\right) inside a captured group. Here are two images to better understanding. Blue parts represent matches and green parts represent captured groups Here is the output I'm getting

Desired output

The first image is a screenshot from regex101 and the second one is an edited image

Please help me with this I'm trying to build a symbolic calculator app. Thanks

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If those two parts are to always be bound by space characters, you could try something like the below: https://regex101.com/r/Lcsxxv/1

regex101.com snip

const regex = /diff\\left\(([^ ]*)\\right\)/gm;
const str   = `diff\\left(5x^2\\right) + diff\\left(5x^2+\\tan\\left(x\\right)\\right)`;

const matches = [];
const groups  = [];

let r;
while ((r = regex.exec(str)) !== null) {
  matches.push(r[0]);
  groups.push(r[1]);
}

console.log(`matches:\n\t${matches.join('\n\t')}
groups:\n\t${groups.join('\n\t')}`)

The way it works is that it's going to look for the last instance of \right) until either the end of the string or a space character, whichever comes first.

I hope this answers your question.

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