【问题标题】:Regex to match the line that ends with the exact word rather than similar words正则表达式匹配以确切单词而不是相似单词结尾的行
【发布时间】:2017-09-25 21:23:08
【问题描述】:

我正在尝试解析配置文件并在 Web UI 上显示输出。但是,我编写的一些正则表达式会返回额外的结果。例如,

lbvs = lb-vs-pr-443-v1-abhishek
lb_vserver_binding = '^bind\s+lb\s+vserver\s+%s\s+([^\s+]+)' %(lbvs)
for line in lb_file_memory:
        if re.match(lb_vserver_binding, line):
            grouped_data = re.search(lb_vserver_binding, line).groups()
            data = grouped_data[0]
            return data

这会返回结果,但也会产生额外的输出。 例如,

绑定 lb vserver lb-vs-pr-443-v1-abhishek lb-sg-pr-443-v1-abhishek

绑定 lb vserver lb-vs-pr-443-v1-abhishek-proxy lb-sg-pr-443-v1-abhishek-proxy

它应该只返回到 abhishek 的第一条记录,但它也返回 abhishek-proxy

我应该如何限制这个?

请提供相同的建议。

【问题讨论】:

  • 您能否更详细地描述您想要匹配的内容?说它应该匹配第一行而不是第二行是不够的。
  • 所以由于 lbvs 是 'lb-vs-pr-443-v1-abhishek' 我希望它只匹配以 abhishek 结尾的条目,就像返回的第一行有 'lb-sg- pr-443-v1-abhishek'。但是,它也会返回具有“abhishek-proxy”、“abhishek-st”、“abhishek-dc”的条目。
  • 所以比赛应该以bind开始,以abhishek结束?
  • 我不知道你是想让它匹配整个第一行还是只匹配lb-vs-pr-443-v1-abhishek
  • 它应该在 'bind lb vserver' 中,然后是任何 lbvs 附带的。就像在这个 lbvs 中是 'lb-vs-pr-443-v1-abhishek' 所以它应该只显示 'bind lb vserver lb-vs-pr-443-v1-abhishek' 的记录而不是 abhishek-proxy

标签: python regex search pattern-matching


【解决方案1】:

如果你想要以'abhishek' 结尾的匹配项,你可以试试这个:

import re
final_list = [line for line in lb_file_memory if re.findall("abhishek$", line)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 2017-12-23
    • 2018-02-10
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    相关资源
    最近更新 更多