[英]Regular expression to extract a message
我有一個腳本來讀取文件行..並且其中一些行包含錯誤消息..因此,我做了一個循環(這里僅用於一行)來查找那些行並提取消息:
import re
data = "15:31:17 TPP E Line 'MESSAGE': There is a technical problem in the server."
if (re.findall(".*E Line.*",data)):
err = re.match(r'\'MESSAGE\':\s(*$)',data)
print err
我執行此腳本時遇到錯誤:/我希望它返回:
There is a technical problem in the server
如果它們都遵循相同的格式,則不需要正則表達式:
>>> data = "15:31:17 TPP E Line 'MESSAGE': There is a technical problem in the server."
>>> data.rsplit(':', 1)[1]
' There is a technical problem in the server.'
但是如果您必須使用它們...
>>> data = "15:31:17 TPP E Line 'MESSAGE': There is a technical problem in the server."
>>> ms = re.search(r"'MESSAGE': (.*)$", data)
>>> ms.group(1)
'There is a technical problem in the server.'
如果需要,還可以提取其他信息:
>>> ms = re.match(r"(\d\d:\d\d:\d\d)\s+(\S+)\s+(\S+)\s+Line\s+'MESSAGE':\s+(.*)", data)
>>> ms.groups()
('15:31:17', 'TPP', 'E', 'There is a technical problem in the server.')
嘗試這個:
import re
data = "15:31:17 TPP E Line 'MESSAGE': There is a technical problem in the server."
r = re.compile("^.*E Line.*'MESSAGE':[ ]*([^ ].*)$")
m = r.match(data)
if m:
err = m.group(1)
print(err)
當然,您應該在循環外部編譯正則表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.