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

标签 regex

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

相关文章:

python - 正则表达式删除字符串中重复的字符模式

regex - 每行一个输出组,带有组名和组 ID

regex - Perl 正则表达式 -?\d+(? :\.\d+)?

php - 如果字符串中间包含很多空格,/\s+$/u 的表现会非常糟糕

MySQL 字符串模式匹配 - 类似的替代方法

javascript - 将 HTML 作为 JSON 传递的最佳实践

java - 如何指示 url 模式中的一个或多个匹配项?

正则表达式匹配整个句子但有异常(exception)

regex - 在 bash 脚本中的斜线 "/"字符前插入文本

php - 用多次出现的单词完成一个句子