我在python中有以下字符串s
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
值LT; 1-5&GT;可以是数字或字符串,如'abc31'
例如
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'''
有没有办法在dscp之后过滤掉这些值并使用正则表达式将它们放入列表中?
答案 0 :(得分:1)
这就是我要做的,这是对其他答案的一点改进:
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)
和number_list
会给您回复:
['0', 'af31', 'ef', '34', '46']
答案 1 :(得分:0)
试试这个新问题。
ouput = re.findall(r'dscp\s+(.*)\s+',s)
答案 2 :(得分:0)
让前贪婪
#!/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