Python正则表达式匹配整行 [英] Python Regular Expression to Match the Whole line

查看:116
本文介绍了Python正则表达式匹配整行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是脚本编写新手,一直在阅读有关如何使用正则表达式的文章.

I'm new to scripting and have been reading about how to use regular expressions.

我想获取与模式匹配的完整行.

I want to fetch the complete line matching a pattern.

我的输出是:

64 bytes from 33.33.33.33: icmp_seq=9 ttl=254 time=1.011 ms

--- 33.33.33.33 ping statistics ---
10 packets transmitted, 10 packets received, 0.00% packet loss

我尝试编写一个匹配丢包的正则表达式并尝试获取完整的行,但无法使其工作..

I tried writing a regex matching packet loss and tried to fetch the complete line but could not make it to work..

有人可以帮我..

cmd = re.search('(\d*)% packet loss', ping_result[int(i)], re.M|re.I)
print cmd.group()

但是这个输出只打印了

00% packet loss
00% packet loss

推荐答案

首先,您希望在提供正则表达式字符串时使用原始字符串,这是通过在字符串前添加 r 来实现的,否则转义序列将被吸收.

First off, you want to use raw strings when providing the regex string, this is done by prefixing the string with an r, otherwise escape sequences will be absorbed.

\d 将匹配数字,但不会匹配它们之间出现的点.由于您希望将其作为一个组,您将需要 r'(\d+\.\d+)'

\d will match digits, but not the dot that appears between them. Since you want that as a group you'll need r'(\d+\.\d+)'

(如果你使用 search 而不是 match 那么你不需要担心这个):最后你需要一些东西来捕获所有内容也可以用 .* 轻松完成,捕获任意数量的字符.您的搜索模式变为:

(if you use search instead of match then you don't need to worry about this):Finally you'll need something to capture everything in the line up to that number as well, which can be done easily with .*, capturing any amount of characters. Your search pattern becomes:

r'.*(\d+\.\d+)% packet loss'

如果要明确行的开始和结束,请使用 ^(开始)和 $(结束)特殊字符

If you want to be explicit about the start and end of the line, then use the ^ (start) and $ (end) special characters

r'^.*(\d+\.\d+)% packet loss$'

这篇关于Python正则表达式匹配整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆