删除行首的字符,但从第 2 行开始

Remove char at beginning of line, but start at line 2

我正在用 nodejs 创建一个 .csv 文件。 文件内容来自几个数组

我将 , 替换为 ;,因此 .csv 格式可以正常工作。

现在我遇到了一个小问题:从我的 CSV 文件的第 2 行开始,每行的开头都有分号。

这是一个例子:

14-07-2020;intLAMi_IgnRate1;intLAMi_IgnRate2
;22:00:00;59.020397;48.343338;51.309185

现在,因为我需要使用 npm 包 replace-in-file, 即时消息替换为以下代码:

const replace = require('replace-in-file')
const options = {
      files: f,
      from: [/,/g, /^;/g],
      to: [';', ' ']
    }

replace(options)
    .then(() => {
        resolve(true)
    })

我的问题是,我不太习惯使用正则表达式。

上面的代码替换了所有 , 但似乎正则表达式 /^;/g 不起作用

有人知道为什么我的代码不起作用吗?

/^;/g在文件开头搜索分号,因为^(有些软件会逐行拆分字符串,所以这种情况下^指的是行首,因此混乱)。

试试

const options = {
   files: f,
   from: [/,/g, /\n;/g],
   to: [';', "\n"]
}

如果将整个文件作为字符串读取,还可以使用 replace 函数:

fileContent.replace(/,/gi, ';').replace(/\n;/gi, "\n")

/^;/gm 应该适用于分号引导线。

When the multiline (m) flag is enabled, beginning and end anchors (^ and $) will match the start and end of a line, instead of the start and end of the whole string.

Global search (g), retains the index of the last match, allowing subsequent searches to start from the end of the previous match. Without the global flag, subsequent searches will return the same match.

让我向您介绍正则表达式方面的新好朋友。 https://regexr.com.