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

234
Views
regex replace only outer brackets of nested parenthesis

Looking to preserve inner nested brackets when replacing brackets. If possible to make many nested layers work that would be great, if not just nested once is fine.

(if money>5 and (times + total_cash >266))[something]
(if times + total_cash >266)[something]

{if money>5 and (times + total_cash >266)}[something]
{if times + total_cash >266}[something]

A naive attempt doesn't seem to work that well:

str.replace(/\(if(.*?)\)]/gi, '{if $1}')
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

for zero level of nesting:

str.replace(/\(if\s*([^()]*)\)/gi, '{if $1}')

for one level (or less):

str.replace(/\(if\s*([^()]*(?:\([^()]*\)[^()]*)*)\)/gi, '{if $1}')

for two levels (or less):

str.replace(/\(if\s*([^()]*(?:\([^()]*(?:\([^()]*\)[^()]*)*\)[^()]*)*)\)/gi, '{if $1}')

etc. This method becomes quickly limited.

Javascript regexes don't have features like recursive patterns (perl, pcre), or a counter system like in .net languages. That's why, the best option is to build a state machine to count the number of opening and closing parenthesis (note that you can use a regex to split your string to interesting parts to do it, for example: str.split(/(\bif\b|[()])/i)).


Note that [^()]*(?:\([^()]*\)[^()]*)* is an optimized way to write: (?:[^()]|\([^()]*\))* (that is shorter but inefficient). This subpattern is unrolled.

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!