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

142
Views
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 answers
Answer question

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