gpt4 book ai didi

regex - 正则表达式 : repeating groups only getting last group

转载 作者:行者123 更新时间:2023-12-01 10:40:24 25 4
gpt4 key购买 nike

我的数据:

stack: 123 overflow: 456 others: - st: 7 ov: 7 againothers: - m: 11 t: 12 - m: 13 t: 14 - m: 15 t: 16 - st: 8 ov: 8 againothers: - m: 17 t: 18 end: 42

我的正则表达式:

^stack: (\d+) overflow: (\d+) others: ?(.+) end: (\d+)$

匹配组为:

1: 123
2: 456
3: - st: 7 ov: 7 againothers: - m: 11 t: 12 - m: 13 t: 14 - m: 15 t: 16 - st: 8 ov: 8 againothers: - m: 17 t: 18
4: 42

到目前为止还不错。然后在第 3 组运行以下正则表达式:

^(?:- st: (\d+) ov: (\d+) againothers: ?(?: - m: (\d+) t: (\d+))+)+$

那根本不起作用(为什么?),所以我删除了 ^$ 并且它匹配了。比赛看起来像这样:

1: 7     // <-- Works as expected.
2: 7
3: 15 // <-- Here I'd expected 2 groups matching: (13,14), (15,16)
4: 16 // <-- but I'm only getting the last group.
1: 8 // <-- This works and the remainder is as expected.
2: 8
3: 17
4: 18

我似乎缺少匹配一个或多个 (?: - m: (\d+) t: (\d+))+ 组合的内部组“13、14”。

在线测试:http://gskinner.com/RegExr/?33urf,以防被屠杀,我的数据是:- st: 7 ov: 7 againothers: - m: 11 t: 12 - m: 13 t: 14 - m: 15 t : 16 - st: 8 ov: 8 againothers: - m: 17 t: 18 正则表达式是:(?:- st: (\d+) ov: (\d+) againothers: ?( ?: - m: (\d+) t: (\d+))+)+.

我读过 http://www.regular-expressions.info/captureall.html ,我认为我的问题与此有关?任何提示/指针/帮助,以便我可以匹配一个或多个 m:t: 组合?

最佳答案

大多数正则表达式引擎不允许从重复组中的同一组括号中进行多次捕获。如果捕获括号匹配多次,您将获得最后匹配的结果。

最简单的解决方法是只为该子模式制作一个正则表达式,然后在每次匹配时获取捕获的结果。

换句话说,首先获取字符串的相关部分,然后在其上使用如下正则表达式:

/ - m: (\d+) t: (\d+)/

(使用您的语言使用的任何机制来匹配所有)。

关于regex - 正则表达式 : repeating groups only getting last group,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15136998/

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