首页 > 解决方案 > 找不到此模式的正则表达式

问题描述

对于 dotnet 应用程序,我有一个字符串模式,如下所示:

TEAM AND CO TEAM
TESTER
Name anderson rahul alice

我只需要捕获“Name”的值,但是只有当字符串序列“TEAM AND CO TEAM”在一行中并且“TESTER”在下一行并且“Name”出现时才会捕获name的值在下一行。

下面是我的正则表达式,但它也选择了第二次出现的名称,我不需要:

\bName\s+(.*)$

输入字符串:

TEAM AND CO TEAM
TESTER
Name anderson rahul alice

LTest SYNC DIM TESTER
PHYSICS
Name KIM SID andy

任何帮助都将是可观的。

正则表达式的屏幕截图

标签: c#asp.netregex

解决方案


利用

(?m)(?<=^TEAM AND CO TEAM\r?\nTESTER\r?\nName\s).+

请参阅正则表达式证明

解释

--------------------------------------------------------------------------------
  (?m)                     set flags for this block (with ^ and $
                           matching start and end of line) (case-
                           sensitive) (with . not matching \n)
                           (matching whitespace and # normally)
--------------------------------------------------------------------------------
  (?<=                     look behind to see if there is:
--------------------------------------------------------------------------------
    ^                        the beginning of a "line"
--------------------------------------------------------------------------------
    TEAM AND CO TEAM         'TEAM AND CO TEAM'
--------------------------------------------------------------------------------
    \r?                      '\r' (carriage return) (optional
                             (matching the most amount possible))
--------------------------------------------------------------------------------
    \n                       '\n' (newline)
--------------------------------------------------------------------------------
    TESTER                   'TESTER'
--------------------------------------------------------------------------------
    \r?                      '\r' (carriage return) (optional
                             (matching the most amount possible))
--------------------------------------------------------------------------------
    \n                       '\n' (newline)
--------------------------------------------------------------------------------
    Name                     'Name'
--------------------------------------------------------------------------------
    \s                       whitespace (\n, \r, \t, \f, and " ")
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  .+                       any character except \n (1 or more times
                           (matching the most amount possible))

推荐阅读