【问题标题】:python regular expression errorpython正则表达式错误
【发布时间】:2016-11-19 06:24:51
【问题描述】:

我正在尝试进行模式搜索,如果匹配,则在计数器值上设置一个位数组。

runOutput = device[router].execute (cmd)
            runOutput = output.split('\n')
            print(runOutput)
            for this_line,counter in enumerate(runOutput):
                print(counter)
                if  re.search(r'dev_router', this_line) :
                    #want to use the counter to set something

得到以下错误:

如果 re.search(r'dev_router', this_line) :

2016-07-15T16:27:13:%错误:文件 “/auto/pysw/cel55/python/3.4.1/lib/python3.4/re.py”,第 166 行,

在搜索 2016-07-15T16:27:13: %-ERROR: return _compile(pattern, flags).search(string)

2016-07-15T16:27:13: %-ERROR: TypeError: 预期的字符串或缓冲区

【问题讨论】:

    标签: python regex


    【解决方案1】:

    您混淆了 enumerate() 的参数 - 首先是索引,然后是项目本身。替换:

    for this_line,counter in enumerate(runOutput):
    

    与:

    for counter, this_line in enumerate(runOutput):
    

    在这种情况下,您将得到一个TypeError,因为this_line 是一个整数,而re.search() 需要一个字符串作为第二个参数。演示:

    >>> import re
    >>>
    >>> this_line = 0
    >>> re.search(r'dev_router', this_line)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/Users/user/.virtualenvs/so/lib/python2.7/re.py", line 146, in search
        return _compile(pattern, flags).search(string)
    TypeError: expected string or buffer
    

    顺便说一句,像 PyCharm 这样的现代 IDE 可以静态检测到这类问题:

    (此截图使用 Python 3.5)

    【讨论】:

    • 然后计数器可以是一些简单的东西:循环之前counter = 0,如果匹配counter += 1
    猜你喜欢
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多