【问题标题】:Python re.search exact match on variablePython re.search 变量的完全匹配
【发布时间】:2023-04-01 16:12:01
【问题描述】:

iplist.txt的内容是这样的格式:

CART    6385    Cell IP: 10.10.10.10
CART    3854    Cell IP: 10.10.10.10
CART     385    Cell IP: 10.10.10.10

我需要帮助获取下面的 python 脚本以仅匹配 385 并打印结果。

我的代码:

IPList = open('iplist.txt','r')    
CartID = raw_input('What is the Cart ID? ')

for line in IPList:            
    if re.search(CartID, line):
        print line.strip()

输出:

What is the Cart ID? 385
CART    6385    Cell IP: 10.10.10.10
CART    3854    Cell IP: 10.10.10.10
CART     385    Cell IP: 10.10.10.10

我只需要它匹配CART 385

【问题讨论】:

    标签: python variables pattern-matching


    【解决方案1】:

    使用re.match 而不是search 仅匹配行首,然后使用正则表达式元字符将您要查找的数字括起来。在您的情况下,该行以 "CART" 开头,您可以使用 "\s+" (匹配所有空格,这样您就不会得到类似 3385 的内容)括号。

    import os
    import re
    
    # todo: debug - generate test file
    if not os.path.exists('iplist.txt'):
        open('iplist.txt', 'w').write("""CART    6385    Cell IP: 10.10.10.10
    CART    3854    Cell IP: 10.10.10.10
    CART     385    Cell IP: 10.10.10.10""")
    
    CartID = raw_input('What is the Cart ID? ')
    
    with open('iplist.txt') as IPList:
        for line in IPList:
             if re.match(r"CART\s+{}\s".format(CartID), line):
                    print line.strip()
    

    【讨论】:

    • 我没有在你的例子中看到 re.match。
    • @gineraso - 我粘贴了错误的代码版本 - 已修复。
    • 购物车 ID 是什么? 385 Traceback(最近一次调用最后一次):文件“RQ.py”,第 12 行,在 如果 re.match(r"CART \s+{}\s".format(CartID), line):ValueError:零格式中的长度字段名称
    • 您必须使用需要更详细格式字符串的旧版 python。请改用r"CART \s+{0}\s".format(CartID)"(在括号中添加一个零)。
    • 是的,我使用的是 2.6.6。在括号中添加零后,任何输入仍然没有结果。
    【解决方案2】:

    您应该使用单词边界\b 序列或空格\s 序列来限制匹配的行,

    re.match(r'^\S+\s+\b%s\b' % CartID, line)
    

    最后,您将拥有:

    ^    # At the start of the line
    \S+  # Match one or more non-blank chars
    \s+  # Match one or more whitespace chars
    \b   # Word boundary
    %s   # The replaced CartID
    \b   # Word boundary (i.e. followed by whitespace)
    

    【讨论】:

    • 购物车 ID 是什么? 385 Traceback(最近一次调用最后一次):文件“RQ.py”,第 11 行,在 如果 re.match(r'^\S+\s\+\b%d\b' % CartID, line):类型错误:%d 格式:需要一个数字,而不是 str
    • @gineraso,对不起,我忽略了它是一个字符串的事实,而是使用%s
    • 不用担心。使用 %s 我没有得到任何一种模式的结果。
    • 抱歉,“+”前多了一个“\”。现在模式已更正。
    • 使用这个我没有得到任何结果:if re.match(r'^\S+\s\+\b%s\b' % CartID, line):
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多