Search code examples
regexregex-lookaroundsregexp-replace

Regex: Replace any string other than a known fixed string? (delimited by quotes)


I'm trying to match and replace strings of the form

mystring = "string-text"

with

mystring = "XYZ string-text"

if and only if string-text is not equal to red. For example

original-text             replacement
-------------             -----------
mystring = "red"          mystring = "red"
mystring = "green"        mystring = "XYZ green"
mystring = "blue"         mystring = "XYZ blue"
mystring = "reds"         mystring = "XYZ reds"
mystring = "_red"         mystring = "XYZ _red"
mystring = "1ed"          mystring = "XYZ 1ed"
mystring = "ree"          mystring = "XYZ ree"
mystring = ""             mystring = "XYZ "
mystring = "12345678"     mystring = "XYZ 12345678"

mystring = "red" is left untouched and all others are replaced as described. Does there exist a regular expression to achieve this?

The best I could manage is

^mystring = "(?!red)(.*)"$

The capturing group (.*) allows replacement to be printed with mystring = "XYZ \1". This works in most cases but fails for the testcase mystring = "reds"


Solution

  • This is slightly hacky, but you can include the ending quotation mark in the lookahead then in the actual match pattern:

    ^mystring = "(?!red")(.*)"$
    

    Where the substitution is:

    mystring = "XYZ $1"
    

    Try it.