【问题标题】:Regex match capture group multiple times正则表达式匹配捕获组多次
【发布时间】:2021-03-27 14:14:28
【问题描述】:

我想让一个正则表达式捕获两个分隔符之间模式的所有实例。

一个字符模式的简化示例(目标:捕获第一个 x 和最后一个 z 之间的所有 b):

bbxabbcbacbedbzbb
    ^^ ^  ^  ^  

应该捕获 5 个bs。

我尝试了.*x.*(b).*z.*,它只捕获了最后一个b。 (rubular)

【问题讨论】:

  • 在 Rubular 中这样做只是为了好玩,所以 Ruby? Perl、PCRE 也很好。
  • 必须重新打开,因为thisthis最接近 xz 之间匹配,但是在当前的问题中,必须在第一个 @ 之间进行匹配987654333@ 和 last z.

标签: regex


【解决方案1】:

使用

(?: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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多