【问题标题】:RegEx in Python not matchingPython中的正则表达式不匹配
【发布时间】: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


【解决方案1】:

您错过了s 并使用r (raw string):

reg = re.compile(r'publishing service/rest/service\s*/\w+-\w+-\w+-\w+-\w+\sstate\b');
#         here __^                                                  here __^  

【讨论】:

  • 你还应该提到r的用法
  • @ThomasAyoub 无论如何这并不能解决问题。这个正则表达式still does not help.
【解决方案2】:

更新你的正则表达式:

reg = re.compile('publishing service /rest/service /\w+-\w+-\w+-\w+-\w+-* state')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-09
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多