从正则表达式模式中的多次出现中捕获最后一次出现

Capture last occurrence from multiple occurrences in Regex pattern

如何捕获以下所需的捕获?我这样做正则表达式 ONE.*(ONE.) 但它捕获了整个字符串。

记事本++:

1 ONE;TWO;THREE;ONE;FOUR;FIVE
2 TEST
3 TEST
4 TEST
5 TEST

所需捕获:如果 ONE 有 1 个匹配项,则 return ONE;TWO;THREE 否则,如果 ONE 有两个匹配项,则 return ONE;FOUR;FIVE.

在 Toad SQL 中,使用

SELECT REGEXP_SUBSTR(Column, '.*(ONE.*)', 1, 1, NULL, 1)

解释

--------------------------------------------------------------------------------
  .*                       any character except \n (0 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  (                        group and capture to :
--------------------------------------------------------------------------------
    ONE                      'ONE'
--------------------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
  )                        end of 

在 Notepad++ 中,使用

.*\KONE(?:(?!ONE).)*

参见 regex proof

解释

--------------------------------------------------------------------------------
  .*                       any character except \n (0 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  \K                       matc reset operator
--------------------------------------------------------------------------------
  ONE                      'ONE'
--------------------------------------------------------------------------------
  (?:                      group, but do not capture (0 or more times
                           (matching the most amount possible)):
--------------------------------------------------------------------------------
    (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
      ONE                      'ONE'
--------------------------------------------------------------------------------
    )                        end of look-ahead
--------------------------------------------------------------------------------
    .                        any character except \n
--------------------------------------------------------

你可以使用

^.*\K\bONE\b.*

模式匹配:

  • ^ 字符串开头
  • .* 匹配任意字符 0+ 次
  • \K\bONE\b 忘记目前匹配的内容,回溯到最后出现的ONE匹配
  • .* 匹配行的其余部分

Regex demo

您还可以使用 (?:ONE.*)?(ONE.*) 并从第一个捕获组中检索结果。

此正则表达式将始终尝试匹配一行中的两个“一”,但允许您访问与第二个“一”相关的部分。当只有一个是唯一匹配的部分时。

你可以try it here.