Home > Blockchain >  Find, wrap and replace occurrences in a string
Find, wrap and replace occurrences in a string

Time:03-10

I Have a list of prefixes: foo.bar. abc.

Now consider this string:

{\n\"a\":foo.bar.user.email,\n\"b\":\"abc.name\"\n}

How do I find every occurrence of substrings that start with one of my prefixes and then wrap it with ${} and remove quotes (if present)?

For example in the above string the desired output should be:

{\n\"a\":${foo.bar.user.email},\n\"b\":${abc.name}\n}

another example:

The quick abc.brown, fox jumps over the foo.bar.lazy\n"abc.dog"\n

desired output:

The quick ${abc.brown}, fox jumps over the ${foo.bar.lazy}\n${abc.dog}\n

CodePudding user response:

In a very laxed and simplified sense, you could use this as a starting point

"?(?<![a-z])((?:foo\.bar|abc)(?:\.[a-z]*) )"?

Replace ${$1}

https://regex101.com/r/eoWkWA/1

"?
(?<! [a-z] )
(                             # (1 start)
  (?: foo \. bar | abc )
  (?: \. [a-z]* ) 
)                             # (1 end)
"?
  • Related