我对正则表达式很陌生
我有一个看起来像这样的文件:
401190: some text1
401194: some text2
this text should be ignored
40119a: some text3
40119e: some text4
4011a2: some text5
4011a8: some text6
我希望获得 401194(包含)和 4011a2(排除)之间的所有内容。 我的正则表达式目前看起来像这样:
/((?=401194)(.*)(?=4011a2))/s
现在我想匹配它们之间的所有内容,不包括不以数字开头的行。 所以基本上除了
/^[\D]*/gm
使其与“应忽略此文本”不匹配。
如何组合这两个表达式?
答案 0 :(得分:2)
如果您可以使用具有无限量词(如 .NET、python PyPi 正则表达式模块或 Javascript where supported)的后视,您可能会使用:
(?<=^(?=401194).*(?:\n(?!4011a2|401194).*)*)\d.*(?=(?:.*\n)*?4011a2)
模式匹配:
(?<=
正向后视,断言左边的是
^(?=401194).*
断言字符串的开头,断言以 401194 开头(?:\n(?!4011a2|401194).*)*
重复匹配所有不以 4011a2 或 401194 开头的行)
近距离回顾^\d.*
匹配以数字开头的行(?=
正向前瞻,断言右边是
(?:.*\n)*?4011a2
匹配尽可能少的行,直到在开头匹配 4011a2)
关闭前瞻const regex = /(?<=^(?=401194).*(?:\n(?!4011a2|401194).*)*)^\d.*(?=(?:.*\n)*?4011a2)/gm;
const str = `401190: some text1
401194: some text2
this text should be ignored
this text should 123 be ignored
40119a: some text3
this text should 123 be ignored
40119e: some text4
4011a2: some text5
4011a8: some text6`;
console.log(Array.from(str.matchAll(regex), m => m[0]));