如何使用正则表达式将 space 添加到数组

How can I add a space to an array using regex

我有一个文件以不正确的格式输出数据。我正在尝试使用 Javascript 来更正文件的格式。为了让它起作用,我需要做的就是在数字和 A.

之间添加一个 space

问题是我不知道这些数字是多少。

文件的示例输出如下:

NAME 12345A JAMES
NAME 12345A JAMES
NAME 12345A JAMES
NAME 12345A JAMES

期望的输出:

NAME 12345 A JAMES
NAME 12345 A JAMES
NAME 12345 A JAMES
NAME 12345 A JAMES

我无法将 indexOf() 与正则表达式一起使用,因此我尝试先将数据转换为字符串,然后再转换为数组。我已经能够 match 正则表达式的每次出现,但是当我尝试 splice 在我的 space 中时,它不会工作。它似乎不喜欢使用 match.index 作为索引。谁能看出我哪里出错了?

const fs = require('fs');

fs.readFile('fileName.txt', (err, data) => { 
    let regEx = /NAME \d\d\d\d\d/g;
    let convertToArray = data.toString().split("   ");
    console.log(convertToArray);

    while ((match = regEx.exec(convertToArray)) != null) {
        console.log(match.index);
    };

    let addSpace = convertToArray.splice(match.index, 0, ' ');
    console.log(addSpace);

});

您可以直接在数据上使用.replace

data.replace(/NAME \d+(?![ \d])/g, '$& ')

参见regex demo

详情

  • NAME - 子串
  • - 一个 space
  • \d+ - 1+ 位数
  • (?![ \d]) - 没有紧跟 space 或其他数字。

字符串替换模式中的$&指的是整个匹配值

要处理任何白色space,请将模式中的文字 space 替换为 \s