Home > Blockchain >  Regex for multiline string #python [duplicate]
Regex for multiline string #python [duplicate]

Time:10-07

i have a multiline string like this

 InOctets    InUcastPkts    InMcastPkts    InBcastPkts 
393109943         106765         968915           4949 

 OutOctets   OutUcastPkts   OutMcastPkts   OutBcastPkts 
1938573528         566317        5280290          32667 

I receive this string from command on console (i am working with cisco switch) . I am searching for a regex that will get each parameter name as group and value below parameter as value for this group, unfortunately when I want to search for regex patterns it finds only in-arguments and it cuts the match:

match='393957044         106765         9>

I tried with this: (?P<Bytes>\d )\s (?P<Ucast>\d )\s (?P<Mcast>\d )\s (?P<Bcast>\d )

My code looks like this:

    self.write(f"show interfaces {interface} counters ")

    # read until prompt "More" is displayed
    buff = self.read_until('More')
    print(buff)
    # self.session.write(" ")
    # write space to display the rest of the buffer
    match = re.search('(?P<Bytes>\d )\s (?P<Ucast>\d )\s (?P<Mcast>\d )\s (?P<Bcast>\d )'
                         , buff)
    print(match)

String that I've entered above comes from print(buff) Any help?

CodePudding user response:

re.match matches the string at the beginning. You need to use re.search to match anywhere in the string. Its usage is exactly the same, you just need to replace match with search:

match = re.search('(?P<Bytes>\d )\s (?P<Ucast>\d )\s (?P<Mcast>\d )\s (?P<Bcast>\d )'
                  , buff)

From the doc:

re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default).

  • Related