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?
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}}'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.