繁体   English   中英

正则表达式删除某些行

[英]Regex delete certain lines

我有一个 csv 文件,其中有一些包含:行。 我需要完全删除这些行。 这是我到目前为止所做的。

var array = fs.readFileSync('../list/fusion.csv').toString();
var pattern = /^\:/gm;
var best = array.replace(pattern, '');

fs.writeFile('../list/full.csv', best, function (err) {
 if (err) return console.log(err);
});

我尝试用空格替换: 我的模式在 regex101 中有效,但是当我运行代码时什么也没有发生。

如果要删除包含:行,则应指定m标志以允许^匹配每一行的开头,而不仅仅是字符串的开头。 您的模式也应该匹配整行,而不仅仅是:

改变:

var pattern = /^\:/g;

到:

var pattern = /^.*?:.*?$/gm;

您也可以通过这种方式删除具有:的行。 我添加了一个演示,描述如何删除包含不必要字符的整行:在您的.csv文件中

 const regex = /^.*(:).*$/gm; const str = `id,name,age 1,aaboss,11 2,eeboss,18 3,:ddboss,15 4,ccboss,14 :5,aboss,13 6,boss,12 7,boss,100: 8,boss,12 `; const subst = ``; // The substituted value will be contained in the result variable // using replace again to remove the empty lines const result = str.replace(regex, subst).replace(/(^[ \\t]*\\n)/gm, ""); console.log(result);

正则表达式: https ://regex101.com/r/JHeRyl/1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM