在Regex模式中从多个出现中捕获最后一个出现



如何捕获下面所需的捕获?我这样做了RegexONE.*(ONE.),但它捕获了整个字符串。

Notedpad + +:

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

期望捕获:如果ONE有1个匹配,则返回ONE;TWO;THREE;如果ONE有两个匹配,则返回ONE;FOUR;FIVE

可以使用

^.*KbONEb.*

模式匹配:

  • ^字符串
  • 起始
  • .*匹配任意字符0+次
  • KbONEb忘记到目前为止匹配的内容,并回溯到ONE最后出现以匹配它
  • .*匹配剩下的行

Regex演示

在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 1:
--------------------------------------------------------------------------------
ONE                      'ONE'
--------------------------------------------------------------------------------
.*                       any character except n (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
)                        end of 1

在notepad++中,使用

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

参见正则表达式证明。

--------------------------------------------------------------------------------
.*                       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
--------------------------------------------------------

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

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

你可以在这里试试。

最新更新