正则表达式包含

时间:2020-06-14 16:59:20

标签: regex

我有一个配置文件:

config line 1
....
config line n
router mk1
 ip 10.1.1.2
 deviceType t1
 sub config line!
 sub config line 2
 !more sub config
!
 !!!
more config lines
router mk2
 ip 10.1.1.2
 sub config line1
 sub config line 2
 deviceType t2
!

每个路由器块以新行上的路由器一词开头,以!结尾。在新的一行上。一个配置文件可以包含许多路由器块。每个子块都以单个空格开头。子块中的行可以按任何顺序排列。我想选择一个包含特定行的块,例如:deviceType t2。

到目前为止,我可以使用以下命令识别所有路由器块:

(?ms)^router mk.*?^!$

但是我只需要一个包含行deviceType t2的块

3 个答案:

答案 0 :(得分:2)

您可以使用

(?m)^router mk\d+(?:\R(?!router mk\d+$).*)*?\R\s*deviceType t2(?:\R.*)*?\R!$
(?m)^router mk\d+(?:\n(?!router mk\d+$).*)*?\n\s*deviceType t2(?:\n.*)*?\n!$
(?m)^router mk\d+(?:\r?\n(?!router mk\d+$).*)*?\r?\n\s*deviceType t2(?:\r?\n.*)*?\r?\n!$

请参见regex demo。这些变化适用于不同种类的换行符序列,\R匹配任何换行符,\n仅匹配LF换行符,\r?\n匹配CRLF或LF换行符。

详细信息

  • (?m)-启用多行模式
  • ^-行首
  • router mk\d+-router mk和1个以上数字
  • (?:\R(?!router mk\d+$).*)*?-以下模式序列出现0次或多次,但次数尽可能少:
    • \R(?!router mk\d+$)-换行符序列,行尾没有router mk +一个或多个数字
    • .*-尽可能多的0个或多个除换行符以外的字符
  • \R\s*-一个换行符,然后是0+个空格
  • deviceType t2-文字字符串
  • (?:\R.*)*?
  • \R-换行顺序
  • !-!
  • $-行尾。

答案 1 :(得分:1)

不要担心行尾,大多数引擎都具有多行模式

尝试(?m)^router.*\s*(?:^(?!!).*\s*)*?^\s*deviceType\s+t2.*\s*(?:^.*\s*)*?^!

使用最少的步骤,是吗?

demo

答案 2 :(得分:1)

以下正则表达式适用于大多数正则表达式引擎(尽管可能有必要将\R替换为\r?\n)。我使用PCRE(PHP)正则表达式引擎对其进行了测试。

(?m)^router .+\R(?: .*\R)* deviceType t2\R(?: .*\R)*!$

Start your engine!

引擎执行以下操作。

(?m)            : multiline mode (^ and $ match beginning and end of line)
^               : match start of line
router .*\R     : match line beginning 'router ', including terminator
(?: .*\R)*      : match a line including terminator that begins with a
                  space in a non-capture group, execute 0+ times
deviceType t2\R : match line 'deviceType t2', including terminator
(?: .*\R)*      : match a line including terminator that begins with a
                  space in a non-capture group, execute 0+ times
!$              : match the line '!'