簡體   English   中英

Python正則表達式查找數字的最后一次出現

[英]Python Regex to find last occurence of digit

我目前正在努力使用Python中的正則表達式進行過濾。 我正在通過ssh執行命令,並且在stdout中捕獲了它。 這里一切順利,但困難的部分來了。 在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],我只能得到整個數字的第一個數字。 我曾考慮過使用$,但這對任何人都沒有幫助?

好吧,這應該給您您想要的。

(\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',)

您的電話:

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'
  • 混合使用shell和Python絕不是一個好主意-當您可以在Python中完成所有操作時(例如您的情況)
  • 無需正則表達式
  • set()提供唯一性

     with open(<your file name>) as in_file: counts = set(line.rpartition(' ')[2] for line in in_file) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM