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

213
Views
Find and replace complex term in a string using Regex

I Need to wrap any expression in a string (it can be multiline string with many expressions, mixed with regular words) that starts with abc.(efg|xyz).bar. with curly braces.

I'm using find and replace approach using the following Regex:

const MY_REGEX = /"?(?<![a-zA-Z0-9-_])((?:abc\.(efg|xyz\.bar))(?:\.[a-zA-Z0-9-_]*)+)"?/gm
someInput.replace(MY_REGEX, '{{$1}}')

My strategy works fine for simple cases like this:

const input = 'abc.efg.bar.name.first, abc.xyz.role, non.captured.term' 
// outputs: {{abc.efg.bar.name.first}}, {{abc.xyz.role}}, non.captured.term

But fails miserably for a complex inputs like this one:

const input = 'abc.xyz.bar.$func(foos[param[name="primary" and bool=true]].param[name="new"].multiValue)' 
// outputs: {{abc.xyz.bar.}}$func(foos[param[name="primary" and bool=true]].param[name="new"].multiValue)
// Should be: {{abc.xyz.bar.$func(foos[param[name="primary" and bool=true]].param[name="new"].multiValue)}}

I'm looking for a more robust way or better regex to do it. Any suggestions?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Based on the examples you gave, it looks like , should be the delimiter between expressions. So (?:\.[a-zA-Z0-9-_]*)+) to [^,]* to match everything until the next ,.

const MY_REGEX = /"?(?<![a-zA-Z0-9-_])((?:abc\.(efg|xyz\.bar))[^,]*)"?/gm;
console.log('abc.xyz.bar.$func(foos[param[name="primary" and bool=true]].param[name="new"].multiValue)'.replace(MY_REGEX, '{{$1}}'));
console.log('abc.efg.bar.name.first, abc.xyz.role, non.captured.term'.replace(MY_REGEX, '{{$1}}'));

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!