Search code examples
regexregex-groupregexp-replace

Regex replacing text unless it's preceeded with backslashes without the usage of look-behind


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


Solution

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

    Operation Parameter
    Search ([^\\])\{\{\s*PLAYER_NAME\s*}}
    Replace $1 Richard