想用Node脚本替换一下项目里所有的someFunction({ id: 'xxx' })这样的代码,结果发现有很多被分行写了,也就是
let b = someFunction({
id: 'xxx'
});
单行的我这么写const reg = /someFunction(.*?)})/g可以匹配
有没有一种能匹配多行结构的正则表达式,用于替换项目中所有文件中的这种结构的代码?
想用Node脚本替换一下项目里所有的someFunction({ id: 'xxx' })这样的代码,结果发现有很多被分行写了,也就是
let b = someFunction({
id: 'xxx'
});
单行的我这么写const reg = /someFunction(.*?)})/g可以匹配
有没有一种能匹配多行结构的正则表达式,用于替换项目中所有文件中的这种结构的代码?
var code = `let b = someFunction({
id: 'xxx'
});
let c = someFunction({id: 'yyy'});`
const reg = /someFunction\(\{([^(){}]*?)\}\)/g
var result = code.replace(reg, (...args)=>`test(${args[1].trim()})`)
console.log(result)
是的,可以使用正则表达式的 [\s\S] 或者 [^] 来匹配多行结构。其中,[\s\S] 表示匹配任何空白字符或非空白字符,[^] 表示匹配任何字符,包括换行符。
以下是匹配多行结构的正则表达式:
> /someFunction\([\s\S]*?}\);/g
其中,[\s\S]*? 表示匹配任意数量的空白字符或非空白字符,包括换行符,非贪婪模式。
你可以使用 Node.js 的 fs 模块读取并替换文件内容,例如:
const fs = require('fs');
const reg = /someFunction\([\s\S]*?}\);/g;
const dirPath = '/path/to/your/project';
fs.readdir(dirPath, (err, files) => {
if (err) throw err;
files.forEach(file => {
const filePath = `${dirPath}/${file}`;
fs.readFile(filePath, 'utf8', (err, content) => {
if (err) throw err;
const newContent = content.replace(reg, 'yourNewFunction($1)');
fs.writeFile(filePath, newContent, 'utf8', err => {
if (err) throw err;
console.log(`${filePath} updated!`);
});
});
});
});
上述代码会遍历指定目录下的所有文件,匹配正则表达式并替换为新的函数,然后将修改后的内容写回原文件。注意,这个例子中的代码仅供参考,请根据自己的需要进行修改。
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答5.1k 阅读✓ 已解决
3 回答1.8k 阅读✓ 已解决
这样?