[SOLVED] Find, wrap and replace occurrences in a string

Issue

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

Solution

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)
"?

Answered By – sln

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *