Maximus Maximus - 2 months ago 5
Javascript Question

How to match a string with leading and trailing conditions and a matching group

I want to match string

"$USER"
that is not preceded or followed by another quote. I can use negative look-ahead for the trailing quote, but can't figure out how to implement negative look-behind. With this string:

'4' = "$NULL$" AND '3' = """$NULL$" AND '7' = """$NULL$"""


It should match only first
"$NULL$"
. Here is the regexp that I've put up:

("\$NULL\$"|"\$KEY\$")(?!")


But it's missing look-behind.

I've seen many answers suggesting imitating negative look-behind with
replace
function, but I can't understand how this can be done with negative look-ahead and capturing.

Answer

You may use a capturing group and use a backreference in the replacement pattern:

var regex = /(^|[^"])("\$NULL\$")(?!")/g;
var str = `'4' = "\$NULL\$" AND '3' = """\$NULL\$" AND '7' = """\$NULL\$"""`;
console.log(str.replace(regex, "$1[NEW_VAL]$2[/NEW_VAL]"));

Details

  • (^|[^"]) - Group 1 (referred to as $1 from the replacement pattern) capturing the start of string (^) or any char other than "
  • ("\$NULL\$") - Group 2 (referred to as $2 from the replacement pattern) capturing "$NULL$" string
  • (?!") - that is not followed with "
Comments