user3230698
user3230698

Reputation: 53

Filtering values after a string using regex

I have the following string s in python

ip access-list IpAclDscpTest
   10 permit ip any any dscp <value1>
   20 permit ip any any dscp <value2>
   30 permit ip any any dscp <value3>
   40 permit ip any any dscp <value4>
   50 permit ip any any dscp <value5

value<1-5> can be either numbers or string like 'abc31'

example

txt = '''ip access-list IpAclDscpTest
   10 permit ip any any dscp 0
   20 permit ip any any dscp af31
   30 permit ip any any dscp ef
   40 permit ip any any dscp 34
   50 permit ip any any dscp 46'''

Is there any way to filter out the values after dscp and put them in a list using regex?

Upvotes: 0

Views: 117

Answers (3)

Aaron Hall
Aaron Hall

Reputation: 394975

Here's what I would do, it's a bit of a refinement on the other answers:

import re

txt = '''ip access-list IpAclDscpTest
   10 permit ip any any dscp 0
   20 permit ip any any dscp af31
   30 permit ip any any dscp ef
   40 permit ip any any dscp 34
   50 permit ip any any dscp 46'''

regex = r'''dscp\s+ # matches dscp and one or more spaces
            ([a-z0-9]+) # capture group, one or more lowercase alphanumerics
             \s*  # matches possible spaces after (0+)
              $ # this matches every endline (with MULTILINE flag below)
         '''

number_list = re.findall(regex, txt, re.MULTILINE | re.VERBOSE)

and number_list returns you:

['0', 'af31', 'ef', '34', '46']

Upvotes: 1

loki
loki

Reputation: 387

Try this for your new question.

ouput = re.findall(r'dscp\s+(.*)\s+',s)

Upvotes: 0

synthesizerpatel
synthesizerpatel

Reputation: 28036

Make the front greedy

#!/usr/bin/python

input="""
ip access-list IpAclDscpTest
   10 permit ip any any dscp 0
   20 permit ip any any dscp 12
   30 permit ip any any dscp 18
   40 permit ip any any dscp 34
   50 permit ip any any dscp 46
"""

import re

for v in re.findall('.*dscp\s(\d+)', input):
    print v

Upvotes: 0

Related Questions