匹配多行的正则表达式

2024-09-28 21:08:16 发布

您现在位置:Python中文网/ 问答频道 /正文

在为多行匹配正则表达式时遇到问题。 我试过几次,但都不走运。你知道吗

第一次尝试: ((?:\b#显示)(?用法:.*\n?){6} ()

结果:失败。发现这些线可以在5-8之间,有时更少或更多。所以匹配6次是行不通的。你知道吗

第二次尝试: (?<;=#\n)(显示。*?版本)

结果:失败:在任何匹配项上都不匹配,尽管我在其他匹配项上使用了类似的正则表达式并获得了成功。你知道吗

我要匹配的字符串。

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(.*)版本但我不知道如何获取数字,因为它们可以是任何小数的组合,但总是数字。你知道吗


Tags: 字符串lt版本config用法datetimeshowservice
3条回答

尝试将换行符匹配到版本号,然后再不匹配换行符。您可以使用(?sm:show.*\nversion)获得多行行为(使用(?sm:...)设置),然后使用类似于.*$的非多行行为。你知道吗

其中一个答案使用pos.lookahead:

\#\ 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']

您可以使用以下正则表达式:

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

DEMO

pythondemo

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

相关问题 更多 >