0

我目前正在努力通过 Python 中的正则表达式进行过滤。我正在通过 ssh 执行命令,并在标准输出中捕获它。这里一切顺利,但困难的部分来了。在 stdout 中加载的文件的输出如下:

命令执行成功。server.jvm.memory.maxheapsize-count-count = 518979584

命令执行成功。server.jvm.memory.maxheapsize-count-count = 518979584

(多次)。比我要执行一个正则表达式:

stdin, stdout, stderr = ssh.exec_command('cat ~/Desktop/jvm.log')
result = stdout.readlines()
result = "".join(result)
print(result)
line = re.compile(r'\d+\n')
rline = "".join(line.findall(result))
print(rline)

打印(rline)导致

>> 518979584 

>> 518979584

>> 518979584

(也是多次)。我只想打印一次。通过打印 rline[0] 我只能得到整数的第一个数字。我考虑过使用 $ 但这没有帮助,有人吗?

4

3 回答 3

2

那么这应该给你你想要的。

(\d+)\D*$

只需进行搜索,这将为您提供最后出现的数字。

>>> regex = re.compile(r"(\d+)\D*$")
>>> string = "100 20gdg0 3gdfgd00gfgd 400"
>>> r = regex.search(string)
# List the groups found
>>> r.groups()
(u'400',)
于 2013-04-26T09:17:37.620 回答
1

你的线:

rline = "".join(line.findall(result))

正在将返回的列表形式findall转换为字符串,然后rline[0]返回字符串中的第一个字符。

只需从中获取元素line.findall(result)[0]

如下例所示

>>> d = '''
     Command get executed successfully. server.jvm.memory.maxheapsize-count-count =     518979584
... 
...     Command get executed successfully. server.jvm.memory.maxheapsize-count-count = 518979584
... '''
>>> d
'\n\n    Command get executed successfully. server.jvm.memory.maxheapsize-count-count    = 518979584\n\n    Command get executed successfully.     server.jvm.memory.maxheapsize-count-count = 518979584\n'
>>> import re
>>> line = re.compile(r'\d+\n')
>>> rline = "".join(line.findall(d))
>>> rline
'518979584\n518979584\n'
>>> line.findall(d)
['518979584\n', '518979584\n']
>>> line.findall(d)[0].strip() # strip() used to remove newline character - may not be needed
'518979584'
于 2013-04-26T09:19:00.170 回答
0
  • 混合使用 shell 和 Python 从来都不是一个好主意——当你可以用 Python 做所有事情时(比如你的情况)
  • 不需要正则表达式
  • set()提供独特性

    with open(<your file name>) as in_file:
        counts = set(line.rpartition(' ')[2] for line in in_file)
    
于 2013-04-26T09:21:19.320 回答