【问题标题】:REGEX to match multi lines正则表达式匹配多行
【发布时间】:2017-07-26 21:35:12
【问题描述】:

在为多行匹配正则表达式时遇到问题。 我尝试了一些,但没有成功。

第一次尝试: ((?:\b# show)(?:.*\n?){6})

结果:失败。发现线条可以在 5-8 之间的任何地方,有时更少或更多。所以匹配 6 次是行不通的。

第二次尝试: (?

结果:失败:不匹配任何内容,尽管我在其他匹配项上使用了类似的正则表达式并成功。

我正在尝试匹配的字符串。

wgb-car1# show startup-config
Using 6149 out of 32768 bytes
!
! NVRAM config last updated at 15:50:05 UTC Wed Oct 1 2014 by user
!
version 12.4
no service pad
service timestamps debug datetime msec
service timestamps log datetime msec
service password-encryption
!

我正在尝试匹配从节目到版本号的所有内容。

这个正则表达式有效(?s)# show(.*)version,但我不知道如何获取数字,因为它们可以是小数的任意组合,但总是数字。 p>

【问题讨论】:

    标签: python regex


    【解决方案1】:

    您可以使用以下 regex

    (?s)#\sshow\s*(.*?)version\s*([\d.]+)
    

    DEMO

    python (demo)

    import re
    
    s = """wgb-car1# show startup-config
    Using 6149 out of 32768 bytes
    !
    ! NVRAM config last updated at 15:50:05 UTC Wed Oct 1 2014 by user
    !
    version 12.4
    no service pad
    service timestamps debug datetime msec
    service timestamps log datetime msec
    service password-encryption
    !"""
    r = r"(?s)#\sshow\s*(.*?)version\s*([\d.]+)"
    o = [m.group() for m in re.finditer(r, s)]
    print o
    

    【讨论】:

      【解决方案2】:

      尝试将换行符匹配到版本号,然后再不匹配换行符。您可以使用(?sm:show.*\nversion) 来获得多行行为(使用(?sm:...) 设置),然后就像.*$ 一样,非多行。

      【讨论】:

        【解决方案3】:

        一个答案(除其他外)使用 pos。前瞻:

        \#\ show
        ([\s\S]+?)
        (?=version)
        

        a demo on regex101.com


        完整的Python 示例:
        import re
        
        string = """
        wgb-car1# show startup-config
        Using 6149 out of 32768 bytes
        !
        ! NVRAM config last updated at 15:50:05 UTC Wed Oct 1 2014 by user
        !
        version 12.4
        no service pad
        service timestamps debug datetime msec
        service timestamps log datetime msec
        service password-encryption
        !"""
        
        rx = re.compile(r'''
            \#\ show
            ([\s\S]+?)
            (?=version)
            ''', re.VERBOSE)
        
        matches = [match.group(0) for match in rx.finditer(string)]
        print(matches)
        # ['# show startup-config\nUsing 6149 out of 32768 bytes\n!\n! NVRAM config last updated at 15:50:05 UTC Wed Oct 1 2014 by user\n!\n']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-12-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多