简体   繁体   中英

Python Regex pattern matching digits and words question?

I'm having hard time creating a regex pattern and maybe you could help.

1.Target is to get only the result which is in BOLD and not the command with grep xxxx?

var = "grep " +net+ "/mnt/hgfs/IRR/fgen.txt"
f2pat = re.findall(r'^([\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})/\d+',fgen)    
print ("FGEN Command: ",f2pat)

FGEN Command: grep 223.253.0.0/20 /mnt/hgfs/IRR/fgen.txt 223.253.0.0/20

Now I do have two addresses in the output 1 is from the command itself second is the result(bold) and just want to match the result.

  1. Target is get the digits after the word member: AS xxxxx (BOLD)? /mnt/hgfs/IR/FILE/as4431-customers-sc:members: AS 28723 , AS3212

    fpas = re.findall(r'(^members: AS)(?:\\d{1,6})',xxx)

  2. Target is to get/match the ip address(bold) after the work route:? RADB: route: 1.0.0.0/8

    radbpat = re.findall(r'(?<=RADB:)(\\S+ \\S+)(?<=route)(\\S+ \\S+)(?:[\\d]{1,3}).(?:[\\d]{1,3}).(?:[\\d]{1,3}).(?:[\\d]{1,3})/\\d+',who)

My regex patter doesn't work properly.

Thank you

For the first one, it appears that the subnet you want is located at the end of the string, so you can just capture exactly that:

text = 'grep 223.253.0.0/20 /mnt/hgfs/IRR/fgen.txt 223.253.0.0/20'
result = re.match('^.+\s([\d\.\/]+)$', text).group(1)
# result = '223.253.0.0/20'

For the second one, it looks like you just only want to capture the first instance of AS xxxxx , so you can do:

text = '/mnt/hgfs/IR/FILE/as4431-customers-sc:members: AS28723, AS3212'
result = re.match('^.+\b(AS\d+)\b.+$', text).group(1)
# result = 'AS28723'

For the third one, you can reuse the first solution:

text = 'RADB: route: 1.0.0.0/8'
result = re.match('^.+\s([\d\.\/]+)$', text).group(1)
# result = '1.0.0.0/8'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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