我试图在节点JS中替换文件中的代码。我找到了如何替换字符串的答案,但我不知道如何处理更复杂的字符串。
这是我要删除的字符串。
SingularApp.createWithAppInstanceKey(
"123",
"test.com",
singularAppInit,
"user",
"password"
)
我在堆栈中找到了如何替换文件:
var fs = require('fs')
fs.readFile(someFile, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
var result = data.replace(/string to be replaced/g, 'replacement');
fs.writeFile(someFile, result, 'utf8', function (err) {
if (err) return console.log(err);
});
});
但是我不能修改结果变量来用我所需要的替换它。
发布于 2022-09-09 23:03:46
在您的情况下,这个正则表达式应该是有效的:
SingularApp\.createWithAppInstanceKey\(((.|\n)*)\)
。所以你的代码是:
var result = data.replace(/SingularApp\.createWithAppInstanceKey\(((.|\n)*)\)/g, 'replacement');
解释:
SingularApp\.createWithAppInstanceKey
匹配字符串'SingularApp.createWithAppInstanceKey('
((.|\n)*)
匹配任何字符或换行符重复的零或多个times.\)
匹配结束括号。
https://stackoverflow.com/questions/73666223
复制