python - 正则表达式提取消息

标签 python regex

我有一个读取文件行的​​脚本..并且某些行包含错误消息..所以我做了一个循环(这里仅针对一行)来查找这些行并提取消息:

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.')

关于python - 正则表达式提取消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16334512/

相关文章:

python - 使用特定值初始化特定形状的numpy数组

javascript - javascript中的重复数字正则表达式

c# - 匹配组中特定单词模式不同值的正则表达式拆分字符串

javascript - 从字符串中提取特定字符

javascript - 正则表达式 Javascript 在模式中使用变量

python - MongoDB 聚合最近记录并将某些字段匹配到最近 30 天

python - 在 wxPython 中,如何绑定(bind)到循环中的单独对象(包括参数)?

python 匹配列表中的项目以创建新列表

python - 来自 python 2.7.6 和 3.3.3 的不同递归结果

c++ - 在不删除的情况下将字符串拆分为具有多个分隔符的多个字符串?