【问题标题】:Regular Expression : Multiline check problem正则表达式:多行检查问题
【发布时间】:2019-07-24 06:37:47
【问题描述】:

您好,我对这个正则表达式有疑问

!
interface TenGigabitEthernet 1/49
 description Uplink
 no ip address
 switchport
 no shutdown
!
interface TenGigabitEthernet 1/50
 no ip address
 shutdown
!
interface TenGigabitEthernet 1/51
 no ip address
 shutdown
!

我试过这个正则表达式(接口)((.\s.)+),但它不工作,因为它匹配“接口”和文本的其余部分

我需要在第一组“界面”中捕捉,在第二组中我需要所有直到第一次出现“!” 例如: 第一组:

interface

第二组:

TenGigabitEthernet 1/51
 no ip address
 shutdown

我该怎么做?

【问题讨论】:

    标签: java regex multiline


    【解决方案1】:

    试试这个:

    (interface)\s+([^!]+)
    

    Here Is Demo

    【讨论】:

    • (interface) 是第一组,\s - 空格,[^!] - 除了 ! 之外的每个字符,所以它会一直捕捉到它,+ - 1 个或多个最后一个字符。这是第二组。
    • 如果这个答案对你有好处 - 请接受它,马克 V。
    【解决方案2】:

    使用这个:

    (interface)\s*([^!]+) /g

    第一组捕获硬编码的interface。第二组通过跳过前导空格(如果有)来捕获除! 之外的所有内容。全局标志 /g 确保所有匹配。

    Demo

    【讨论】:

      【解决方案3】:

      如果内容本身可以包含!,您可以在行首检查!,然后重复匹配所有行,直到在开头遇到!

      ^(interface)\s*(.*(?:\n(?!!).*)*)
      

      在 Java 中

      String regex = "^(interface)\\s*(.*(?:\\n(?!!).*)*)";
      

      Regex demo

      【讨论】:

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