【发布时间】:2019-01-23 10:46:06
【问题描述】:
with open(file_path, 'r') as logs:
for line in logs.readlines():
reg = re.compile('publishing service \/rest\/service\/\w+-\w+-\w+-\w+-\w+\state\s\w+\b.*');
print(reg.search(line.strip()));
我正在使用上述正则表达式代码进行模式匹配。我的字符串如下
2019-01-17 19:41:40.445 UTC,INFO ,myapp:761,publishing service /rest/service /4ce2c885-3690-48ba-a1cb-bb1762859a39 state
但我的代码无法匹配此字符串。对此有什么建议吗?
【问题讨论】:
-
请注意,您的模式中的
\b是一个退格字符。在正则表达式字符串文字前添加r前缀。此外,字符串中/rest/service之后有一个空格,并且您的模式中没有空格。你应该使用\sstate,\state匹配一个空格和tate。 -
实际要求是什么?请注意,最后的
\s\w+假设state之后有文本,但没有。试试r'publishing service /rest/service\s*/\w+(?:-\w+){4}\sstate\b'。见this demo。 -
使用
r为我工作。谢谢你:)
标签: python regex python-2.7