我有一个字符串:
const str = 'DELETE FROM "organization" WHERE "name" = $1 AND "metadata" = $2 AND "id" = $3';
我需要找到"metadata"
个单词来对其进行修改。我只知道= $2
字后有"metadata"
。
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'
regex
的外观如何? (如果可能的话)
答案 0 :(得分:3)
您可以使用
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'));
正则表达式为"[^"]*"(\s*=\s*\$2\b)
:
"[^"]*"
-一个"
,除了"
以外的0个或更多字符,然后为"
(\s*=\s*\$2\b)
-捕获组1(替换模式中的$1
表示捕获到该组中的值):
\s*=\s*
-一个=
包含0+空格\$
-一个$
字符(必须转义)2\b
-一个2
。