Regular Expression to find word by specific symbols

Viewed 60

I have a string:

const str = 'DELETE FROM "organization" WHERE "name" = $1 AND "metadata" = $2 AND "id" = $3';

I need to find "metadata" word to modify it. I only know that there is = $2 after "metadata" word.

const regex = RegExp(/ = $2/); // just to show what I have
const foundWord = someMagicWithRegex(str, regex); // "metadata"
const newString = str.replace(foundWord, `${foundWord}::text`);
console.log(newString);

'DELETE FROM "organization" WHERE "name" = $1 AND "metadata"::text = $2 AND "id" = $3'

How regex should look? (if its possible)

1 Answers

You may use

var str = 'DELETE FROM "organization" WHERE "name" = $1 AND "metadata" = $2 AND "id" = $3';
console.log(str.replace(/"[^"]*"(\s*=\s*\$2\b)/g, '"NEW METADATA"$1'));

The regex is "[^"]*"(\s*=\s*\$2\b):

  • "[^"]*" - a ", 0 or more chars other than " and then "
  • (\s*=\s*\$2\b) - Capturing group 1 ($1 in the replacement pattern refers to the value captured into this group):
    • \s*=\s* - a = enclosed with 0+ whitespaces
    • \$ - a $ char (must be escaped)
    • 2\b - 2 as a whole word.
Related