gpt4 book ai didi

正则表达式多次匹配捕获组

转载 作者:行者123 更新时间:2023-12-03 18:51:27 24 4
gpt4 key购买 nike

我想让正则表达式捕获两个分隔符之间的模式的所有实例。
一个字符模式的简化示例(目标:捕获第一个 b 和最后一个 x 之间的所有 z ):

bbxabbcbacbedbzbb
^^ ^ ^ ^
应该捕获 5 b s。
我试过 .*x.*(b).*z.*只捕获最后一个 b . ( rubular )

最佳答案


(?:x|(?<!\A)\G).*?\Kb(?=.*z)
regex proof .
说明
--------------------------------------------------------------------------------
(?: group, but do not capture:
--------------------------------------------------------------------------------
x 'x'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
(?<! look behind to see if there is not:
--------------------------------------------------------------------------------
\A the beginning of the string
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
\G where the last m//g left off
--------------------------------------------------------------------------------
) end of grouping
--------------------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
--------------------------------------------------------------------------------
\K match reset operator (omits matched text)
--------------------------------------------------------------------------------
b 'b'
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
.* any character except line breaks (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
z 'z'
--------------------------------------------------------------------------------
) end of look-ahead

关于正则表达式多次匹配捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66832287/

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