我想让正则表达式捕获两个分隔符之间的模式的所有实例。
一个字符模式的简化示例(目标:捕获第一个 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/