2016-07-15 192 views
0

我想做一個模式搜索,如果匹配,然後設置計數器值bitarray。python正則表達式錯誤

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 

得到以下錯誤:

if re.search(r'dev_router', this_line) :

2016-07-15T16:27:13: %ERROR: File "/auto/pysw/cel55/python/3.4.1/lib/python3.4/re.py", line 166,

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

2016-07-15T16:27:13: %-ERROR: TypeError: expected string or buffer

回答

2

你混了論據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可以靜態檢測這樣的問題:

enter image description here

(Python的3.5用於此截圖)

+0

然後計數器可以是這樣簡單的:在循環'counter = 0'之前,並且如果匹配'counter + = 1' –