Python 正则表达式匹配多行
无法为多行匹配正则表达式。 我试过几次,但没有成功 第一次尝试: ((?:\b#show)(?:.*\n?{6}) 结果:失败。发现这些线可以在5-8之间,有时更少或更多。所以匹配6次是行不通的 第二次尝试:Python 正则表达式匹配多行,python,regex,Python,Regex,无法为多行匹配正则表达式。 我试过几次,但没有成功 第一次尝试: ((?:\b#show)(?:.*\n?{6}) 结果:失败。发现这些线可以在5-8之间,有时更少或更多。所以匹配6次是行不通的 第二次尝试: (?您可以使用以下正则表达式: python() 尝试将换行符匹配到版本号,然后再不匹配换行符。您可以使用(?sm:show.*\nversion)来获取多行行为(使用(?sm:…)设置),然后类似于*$这样的非多行操作。一个答案(其中一个)使用pos。向前看: \#\ show ([\
(?您可以使用以下正则表达式: python()
尝试将换行符匹配到版本号,然后再不匹配换行符。您可以使用
(?sm:show.*\nversion)
来获取多行行为(使用(?sm:…)
设置),然后类似于*$
这样的非多行操作。一个答案(其中一个)使用pos。向前看:
\#\ show
([\s\S]+?)
(?=version)
看。
作为完整的
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']
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
\#\ show
([\s\S]+?)
(?=version)
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']