-1

I have this situation where I am trying to replace a bunch of tags in a block of text using regex, however I also wish to allow the user to escape any tags.

Note: I want to avoid look ahead / behind since Safari doesn't support it

Live Example: https://regex101.com/r/mDGs3C/1

Welcome {{ PLAYER_NAME }} to the event

using a substitution this should render

Welcome Richard to the event

For this I was using the following regex, which seems to work correctly.

/{{\s*PLAYER_NAME\s*}}/gm

However I also want the ability to be able to escape, so the following

Welcome {{ PLAYER_NAME }} to the event, you can use tags in here such as \\{{ PLAYER_NAME }}

I want to output as ...

Welcome Richard to the event, you can use tags in here such as {{ PLAYER_NAME }}

So I have tried to use the following at the start of my regular expression to state that I don't want it to match if it contains a double backslash.

/[^\\]{{\s*PLAYER_NAME\s*}}/gm

This ALMOST works, however it cuts off the last letter of the previous word in some scenarios, take a look at my example to see the e being cut off the word welcome

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

Richard Bagshaw
  • 351
  • 2
  • 4

1 Answers1

1

Capture the non-slashes and put them back in the replacement:

Operation Parameter
Search ([^\\])\{\{\s*PLAYER_NAME\s*}}
Replace $1 Richard
Bohemian
  • 389,931
  • 88
  • 552
  • 692
  • 1
    This works perfectly thanks! was just a case of adding it into its own group and than making sure I use that in the replacement :) – Richard Bagshaw Dec 03 '21 at 06:20