【问题标题】:Escape brackets in python regexpython 正则表达式中的转义括号
【发布时间】:2021-10-03 10:40:46
【问题描述】:

我想从下面的字符串日志中搜索子字符串,re.escape 在我的情况下似乎不起作用,我想要一些建议。

log = "xxxxxxxxxxxxxxxxxxxx found targets:['123-321', '123-456'] asdasdasjdlajdlkajdlsk"

node_ids = ['123-321', '123-456']
node_ids = re.escape(str(node_ids))
substr = = f"targets: {node_ids}"
print(node_ids)
print(re.findall(substr, log))

输出

targets: \[\'123\-321\'\,\ \'123\-456\'\]
[]

【问题讨论】:

  • log 不包含带空格的targets:

标签: python python-3.x python-re


【解决方案1】:

问题来了

substr = f"targets: {node_ids}"

这意味着该字符串必须包含targets: 后跟一个空格,而log 中不存在该空格。

>>> import re
>>> log = "xxxxxxxxxxxxxxxxxxxx found targets:['123-321', '123-456'] asdasdasjdlajdlkajdlsk"
>>> node_ids = ['123-321', '123-456']
>>> node_ids = re.escape(str(node_ids))
>>> substr = f"targets:{node_ids}"
>>> print(re.findall(substr, log))
["targets:['123-321', '123-456']"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2023-01-11
    • 1970-01-01
    相关资源
    最近更新 更多