NineTail
NineTail

Reputation: 223

REGEX to match multi lines

Having trouble matching a regex for multiple lines. I've tried a few but with no luck.

First Try: ((?:\b# show)(?:.*\n?){6})

Result: Failed. Found out that the lines can be anywhere between 5-8 sometimes less or more. So matching 6 times won't work.

Second Try: (?<=#\n)(show.*?version)

Result: Failed: Does not match on anything although I've used similar regex with success on other matches.

String I'm trying to match.

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
!

I'm trying to match everything from show to the version number.

This regex works (?s)# show(.*)version but I don't know how to get the numbers as they can be any combination of decimals, but always numbers.

Upvotes: 1

Views: 121

Answers (3)

m87
m87

Reputation: 4523

You could use the following 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

Upvotes: 1

Jan
Jan

Reputation: 43169

One answer (among others) uses a pos. lookahead:

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

See a demo on regex101.com.


As full Python example:

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

Upvotes: 0

aghast
aghast

Reputation: 15300

Try matching newlines up to the version number, and then not matching newlines afterwards. You can use (?sm:show.*\nversion) to get the multi-line behavior (with the (?sm:...) settings) and then just something like .*$ afterwards, non-multiline.

Upvotes: 0

Related Questions