简体   繁体   English

Python Regex模式匹配数字和单词的问题?

[英]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? 1.目标是仅获取以粗体显示的结果,而不是使用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 FGEN命令: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是命令本身的第二个地址,第二个是result(bold),只想匹配结果。

  1. Target is get the digits after the word member: AS xxxxx (BOLD)? 目标是在单词成员后得到数字:AS xxxxx (BOLD)? /mnt/hgfs/IR/FILE/as4431-customers-sc:members: AS 28723 , AS3212 / mnt / hgfs / IR / FILE / as4431-customers-sc:members:AS 28723 ,AS3212

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

  2. Target is to get/match the ip address(bold) after the work route:? 目标是在工作路线之后获取/匹配IP地址(粗体):? RADB: route: 1.0.0.0/8 RADB:路线: 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) radbpat = re.findall(r'(?<= RADB:)(\\ S + \\ S +)(?<= route)(\\ S + \\ S +)(?:[\\ d] {1,3})。(?: [\\ d] {1,3})(:?[\\ d] {1,3})(:?[\\ d] {1,3})/ \\ d +”,谁)

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: 对于第二个实例,您似乎只想捕获AS xxxxx的第一个实例,因此您可以执行以下操作:

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'

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

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