简体   繁体   English

使用正则表达式过滤字符串后的值

[英]Filtering values after a string using regex

I have the following string s in python 我有以下字符串s在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' value <1-5>可以是数字,也可以是字符串,例如'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? 有什么方法可以过滤出dscp之后的值,并使用正则表达式将它们放在列表中?

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: number_list返回您:

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

试试这个新问题。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM