【问题标题】:Python - Return some characters after phrase in stringPython - 在字符串中的短语后返回一些字符
【发布时间】:2015-05-01 17:36:53
【问题描述】:

我想捕获字符串中某个单词后面的一些字符。例如,

Pinging 10.1.1.1 with 32 bytes of data:

Reply from 10.1.1.1: bytes=32 time=39ms TTL=253

Reply from 10.1.1.1: bytes=32 time=17ms TTL=253

Reply from 10.1.1.1: bytes=32 time=17ms TTL=253 

Reply from 10.1.1.1: bytes=32 time=17ms TTL=253

Ping statistics for 10.1.1.1:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds:
    Minimum = 17ms, Maximum = 39ms, Average = 22ms

我想在 time= 之后获取字符,但在第一个 time= 实例的 TTL 之前停止空格

我知道我可以对 time= 进行拆分并获取后面的字符,但我不知道如何让它在 TTL 之前停止(例如,数字可能超过 2 位,所以只需获取 4以下不是一个选项)

也许正则表达式也是一种选择?我已经看到像(?:time=).* 这样的东西会获得第一个实例,但是我再次不确定如何指定它在 ms 之后停止。

编辑 - 添加最终代码,现在它正在工作。感谢大家的帮助!

import os
import subprocess
import re

#Define Target
hostname = raw_input("Enter IP: ") 

#Run ping and return output to stdout.
#subprocess.Popen runs cmdline ping, pipes the output to stdout. .stdout.read() then reads that stream data and assigns it to the ping_response variable
ping_response = subprocess.Popen(["ping", hostname, "-n", '1'], stdout=subprocess.PIPE).stdout.read()

word = "Received = 1"



latency = 1

p = re.compile(ur'(?<=time)\S+')
x = re.findall(p, ping_response)

if word in ping_response:
print "Online with latency of "+x[0]

else:
print "Offline"

【问题讨论】:

  • 你是如何运行 ping 的?
  • @PadraicCunningham 我将我正在使用的代码添加到问题中。谢谢!
  • @PadraicCunningham 是的。
  • 好吧,我想说你可以用 grep 输出,因为它是 windows,更简单的方法是简单地使用 check_output

标签: python regex string


【解决方案1】:

试试这个正则表达式

(?<=time=)\S+

这应该为您使用re.findall

See demo here

import re
p = re.compile(ur'(?<=time=)\S+')
test_str = u"\n\n Pinging 10.1.1.1 with 32 bytes of data:\n\n Reply from 10.1.1.1: bytes=32 time=39ms TTL=253\n\n Reply from 10.1.1.1: bytes=32 time=17ms TTL=253\n\n Reply from 10.1.1.1: bytes=32 time=17ms TTL=253\n\n Reply from 10.1.1.1: bytes=32 time=17ms TTL=253\n\n Ping statistics for 10.1.1.1: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 17ms, Maximum = 39ms, Average = 22ms\n"     
re.findall(p, test_str)

【讨论】:

  • @BhargavRao 嗨!!!!!!!!!!是的!!!!长途旅行 :P........stackoverflow.com/questions/29988595/… 见 dis!!!!!!! Anti happala 的精彩回答.......总有一些东西可以向 SO 学习!!!!!!!!!
  • 如果我在一个名为 ping_response 的变量中有我的示例字符串(以“Pinging”开头的字符串),对于您开始的行 [test_str = u"\n\n ..."]我只是把 [test_str = u ping_response] ?
  • 我如何输出该数据?我有 {p = re.compile(ur'(?
  • @Abraxas 使用 x=re.findall(p, test_str) x 将成为所有时间的列表
  • @Abraxas (?&lt;=time[&lt;=])\S+
【解决方案2】:

使用正则表达式,但要保持简单:不要先行/后视,而是使用捕获组的老式方法:

>>> times = re.findall(r"time=(.*?) ", pingdata)
>>> times
['39ms', '17ms', '17ms', '17ms']

解释:.*? 是一个非贪婪的正则表达式,所以它会在括号后的空格匹配时立即停止。这完全符合您的要求。带有捕获表达式的re.findall() 将返回括号内的匹配项,而不是整个匹配项。

如果您只想要第一个匹配项(正如您在问题中所说,我现在注意到了),请使用 times[0] 或使用 re.search 代替,这将返回第一个匹配项(但作为匹配对象,因此您提取捕获的组)。

>>> m = re.search(r"time=(.*?) ", pingdata)
>>> m.group(1)
'39ms'

【讨论】:

  • 由于我对此很陌生,我能否验证 'pingdata' 是我的 ping 响应字符串的变量,然后澄清我将如何在我的响应中显示这个数字(即:[print"在线延迟为 %s" % 延迟] 是否延迟 = m.group(1)?
  • 是的,pingdata 是一个包含整个 ping 响应的字符串。 m.group(1) 也是一个字符串,所以你可以按照你的建议使用它(或者干脆"Online with latency "+m.group(1)
  • 不客气。 PS。如果你刚刚开始,我建议升级到 python 3。它现在已经非常成熟并且得到很好的支持,没有理由使用 python 2,除非你因为某种原因别无选择。
  • 我对 Zed Shaw 的书“Learn Python the Hard Way”有一点了解,他实际上说的正好相反,但我很高兴听到不同的意见。我只是希望能够胜任一些脚本和编程来帮助我的系统管理员工作。我一定会去看的!再次感谢
  • 这本书是什么时候写的?各种第三方库转换为 python 3 需要一段时间,但现在尘埃落定。 python 3 中已经有很多 python 2 缺少的东西。如果你希望用非英文文本做任何事情,你绝对应该切换。
【解决方案3】:
test = 'Reply from 10.1.1.1: bytes=32 time=39ms TTL=253'
test.split()[4].split('=')[1]

一步一步:

test.split()
['Reply', 'from', '10.1.1.1:', 'bytes=32', 'time=39ms', 'TTL=253']
test.split()[4].split('=')
'time=39ms'
test.split()[4].split('=')
['time', '39ms']
test.split()[4].split('=')[1]
'39ms'

输出:

#1 '39ms'

另一个测试:

test = 'Reply from 10.1.1.1: bytes=32 time=38833434343434349ms TTL=253'
test.split()[4].split('=')[1]
'38833434343434349ms'

【讨论】:

  • 我认为这行不通,时间值可能是 2940 毫秒或 374 毫秒,所以并不总是 5 个字符
  • 它会起作用的。 .split()[4] 获取拆分字符串后创建的列表的第 5 个元素。长度可以是n
  • 哦,好吧,这是有道理的,我没有意识到它是用空格分割字符串并将每个子字符串视为一个元素。谢谢!
  • 输出中的其他行呢?
  • @PadraicCunningham - 这是假设 OP 一次只使用一个字符串。
猜你喜欢
  • 2014-12-17
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-23
  • 2012-03-27
  • 2012-05-06
  • 1970-01-01
相关资源
最近更新 更多