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

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

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 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