求问个正则问题?

想用Node脚本替换一下项目里所有的someFunction({ id: 'xxx' })这样的代码,结果发现有很多被分行写了,也就是

let b = someFunction({
    id: 'xxx'
});

单行的我这么写const reg = /someFunction(.*?)})/g可以匹配
有没有一种能匹配多行结构的正则表达式,用于替换项目中所有文件中的这种结构的代码?

阅读 2.1k
5 个回答
/aa\s*\(\s*{\s*id\s*:\s*["'].+?["']\s*}\s*\)/

这样?

/someFunction(.*?)\s(.*?)\s(\}\))/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!`);
      });
    });
  });
});

上述代码会遍历指定目录下的所有文件,匹配正则表达式并替换为新的函数,然后将修改后的内容写回原文件。注意,这个例子中的代码仅供参考,请根据自己的需要进行修改。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题