gpt4 book ai didi

javascript - .exec() 和 .split() 的 RegExp 工作方式不同

转载 作者:行者123 更新时间:2023-11-30 23:59:08 25 4
gpt4 key购买 nike

我尝试使用 .split(' - ') 将航类中转拆分到不同的机场,但有一个机场的名称中包含此字符。因此,我现在被迫使用正则表达式。我不知道为什么,但是当我执行 reg.exec(a) 时,它只找到一个字符(正确!),但是当我执行 .split(reg) 时,它只找到一个字符它分成三部分而不是两部分。

任何人都知道为什么会发生这种情况以及我可以用它做什么,以便我可以使用此模式进行分割

代码:

const a = "Cristoforo Colombo Airport, Genoa, Italy (GOA) - Augsburg - Muehlhausen Airport, Munich, Germany (AGB)"
const b = "Augsburg - Muehlhausen Airport, Munich, Germany (AGB) - Strachowice Airport, Wroclaw, Poland (WRO)"

const reg = /(?<=,.*,.*) - /

console.log(reg.exec(a))

console.log(a.split(reg))
console.log(b.split(reg))

代码示例链接:https://repl.it/repls/AltruisticUnitedSmalltalk

链接到 RegEx101:https://regex101.com/r/8HOSpz/4

最佳答案

模式

您的分割模式具有可变长度的后向断言,这会导致重叠:

Cristoforo Colombo Airport, Genoa, Italy (GOA) - Augsburg -
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Satisfies the assertion
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Also satisfies the assertion

关于exec

您只看到 exec 返回了一个匹配项,因为未指定 /g(全局)标志;启用全局标志后,调用一次将返回第一个匹配项,但如果再次调用它,则会返回另一个结果:

const a = "Cristoforo Colombo Airport, Genoa, Italy (GOA) - Augsburg - Muehlhausen Airport, Munich, Germany (AGB)"
const reg = /(?<=,.*,.*) - /g
let match

while ((match = reg.exec(a)) !== null) {
console.log(`Found ${match[0]}. Next starts at ${reg.lastIndex}.`);
}

关于分割

当使用正则表达式调用 split() 时,它会隐式复制为启用了全局标志的表达式;然后它会迭代这些匹配项,如上面的代码片段所示,并根据这些结果创建一个字符串切片数组。

替代方案

据我所知,所有机场的名称末尾都在括号内有一个呼号;因此,您的后视断言可以这样修复:

const a = "Cristoforo Colombo Airport, Genoa, Italy (GOA) - Augsburg - Muehlhausen Airport, Munich, Germany (AGB)"
const b = "Augsburg - Muehlhausen Airport, Munich, Germany (AGB) - Strachowice Airport, Wroclaw, Poland (WRO)"

const reg = /(?<=\)) - /

console.log(a.split(reg))
console.log(b.split(reg))

关于javascript - .exec() 和 .split() 的 RegExp 工作方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60851757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com