首页 > 解决方案 > 管道文件时如何使javascript正则表达式匹配所有行

问题描述

如果我将数据上的正则表达式作为字符串运行,我的三行匹配没有问题。

https://regex101.com/r/pHsTvV/1

const regex = /(?<email>((?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])))\s*\|\s*(?<name>([a-zA-Z]{2,}\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\s?([a-zA-Z]{1,})?))\s*\|\s*(?<address>.*)\s*\|\s*(?<country>(\w|\.|\s*){1,})\s*\|\s*(?<phone>(\d|-|\ |\+|\(|\)|\.|\/){7,})/gm;
const str = `john.doe@gmail.test| John Doe| 160 Boston Rd| Chelmsford MA 11824| United States| 00088782000
jane.doe@aol.test| Jane Doe| 8415 45th St| Lyons IL 60534| United States| 0005800000
alicia.random123@gmail.test| Alicia Random| BLK 8, City Point| No.58 Wing Shun Street| Tsuen Wan| Not in U.S.| +00092262000`;

const lines = str.split('\n')
lines.forEach(line => {
    const test = regex.exec(str)
    if (test && test.groups) {
        console.dir(test.groups)
    } else {
        console.log('could not match')
    }
});

但是,当我从 txt 文件加载数据时,javascript 总是给我两行不匹配的行:

const regex = /(?<email>((?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])))\s*\|\s*(?<name>([a-zA-Z]{2,}\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\s?([a-zA-Z]{1,})?))\s*\|\s*(?<address>.*)\s*\|\s*(?<country>(\w|\.|\s*){1,})\s*\|\s*(?<phone>(\d|-|\ |\+|\(|\)|\.|\/){7,})/gm;
import * as fs from 'fs';
import * as path from 'path';
import * as es from 'event-stream';
const filePath = path.join(process.cwd(), 'data/test.txt')
var s = fs.createReadStream(filePath)
    .pipe(es.split())
    .pipe(es.mapSync(function (line: string) {
        let values = regex.exec(line.trim())
        if (values && values.groups) {
            console.dir(values.groups)
        } else {
            console.log(`COULD NOT MATCH`)
            console.log(line)
        }
    }).on('error', function (err) {
        console.log('Error while reading file.', err);
    })
        .on('end', function () {
            console.log('Read entire file.')
        })
    )

test.txt 文件如下:

john.doe@gmail.test| John Doe| 160 Boston Rd| Chelmsford MA 11824| United States| 00088782000
jane.doe@aol.test| Jane Doe| 8415 45th St| Lyons IL 60534| United States| 0005800000
alicia.random123@gmail.test| Alicia Random| BLK 8, City Point| No.58 Wing Shun Street| Tsuen Wan| Not in U.S.| +00092262000

即使在一个有 100 行的文件上,也总是有两行中的一行不匹配。当我阅读文件时,jane.doe@aol.test不匹配

我尝试了以下方法来查看它是否特定于行:

const regex = /(?<email>((?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])))\s*\|\s*(?<name>([a-zA-Z]{2,}\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\s?([a-zA-Z]{1,})?))\s*\|\s*(?<address>.*)\s*\|\s*(?<country>(\w|\.|\s*){1,})\s*\|\s*(?<phone>(\d|-|\ |\+|\(|\)|\.|\/){7,})/gm;
const uniqueStr = `jane.doe@aol.test| Jane Doe| 8415 45th St| Lyons IL 60534| United States| 0005800000`

const test = regex.exec(uniqueStr)
if (test && test.groups) {
    console.dir(test.groups)
} else {
    console.log('could not match')
    console.log(uniqueStr)
}

这不匹配,但如果我在 regex101 上尝试正则表达式,则没有匹配问题。

https://regex101.com/r/52kpRD/1

标签: javascriptregexpipe

解决方案


看看这个问题的公认答案: RegExp is Stateful

本质上,您regex是一个对象,它将索引保留在找到最后一个匹配项的行中,下一次它从那里继续,而不是再次从该行的开头寻找匹配项

regex.lastIndex因此,一种解决方案是在每次调用时手动重置es.MapSync

像这样:

let s = fs.createReadStream(filePath)
    .pipe(es.split())
    .pipe(es.mapSync(function (line) {
            regex.lastIndex = 0; //Reset the RegExp index
            let values = regex.exec(line.trim())
            if (values && values.groups) {
                console.dir(values.groups)
            } else {
                console.log(`COULD NOT MATCH`)
                console.log(line)
            }
        }).on('error', function (err) {
            console.log('Error while reading file.', err);
        })
            .on('end', function () {
                console.log('Read entire file.')
            })
    )

请注意,这只会发生,因为regex它是全局定义的。如果您要在mapSync()回调中分配正则表达式,它应该具有相同的效果。但是,重置lastIndex更简单,可能更高效。


推荐阅读