正则表达式删除某些行

时间:2018-09-08 15:47:21

标签: javascript regex

我有一个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中使用,但是当我运行代码时,什么也没发生。

2 个答案:

答案 0 :(得分:0)

如果要删除包含format date date9. time time8. ; 的行,则应指定:标志以允许m匹配每行的开头,而不只是字符串的开头。您还应该将您的模式设置为与整行匹配,而不仅仅是^

更改:

:

收件人:

var pattern = /^\:/g;

答案 1 :(得分:0)

您也可以通过这种方式删除具有:的行。我添加了一个演示,描述了如何删除:文件中包含不必要字符.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