2015-05-11 42 views
1

因此,我有一個CSV文檔,每行都有一個元數據,一個XPATH和一個正則表達式字符串。該腳本使用xpath遍歷API請求,然後我想使用存儲在CSV中的正則表達式與該xpath一起搜索API結果中的某些內容。我的問題是如何使用CSV行中的數據作爲文字正則表達式搜索字符串,如r'^\w{2}.+'與要針對的字符串進行搜索。在Python中使用re作爲正則表達式字符串值

with open(rules, 'r+') as rulefile: 
    rreader = csv.DictReader(rulefile) 
    for row in rreader: 
     for ip, apikey in keydict.iteritems(): 
      rulequery = {'type': 'config', 'action': 'get', 'key': apikey, 'xpath': row["xpath"]} 
      rrule = requests.get('https://' + ip + '/api', params = rulequery, verify=False) 
      rrex = re.compile('{}'.format(row["regex"]), re.MULTILINE) 
      for line in rrule.text: 
       config = rrex.findall(line) 
       print(config) 
+0

問題是什麼?它不起作用?你有錯誤嗎? – Spirine

+0

不只是返回... [] [] [] [] [] [] [] [] [] [] –

回答

1

所以我想我可能已經找到了解決辦法,但林不知道它是最好的......打開尋求幫助,如果任何人有更好的方式來做到這一點。

with open(rules, 'r+') as rulefile: 
rreader = csv.DictReader(rulefile) 
for row in rreader: 
    for ip, apikey in keydict.iteritems(): 
     regex = row["regex"] 
     rulequery = {'type': 'config', 'action': 'get', 'key': apikey, 'xpath': row["xpath"]} 
     rrule = requests.get('https://' + ip + '/api', params = rulequery, verify=False) 
     config = re.search(regex, rrule.text) 
     print rrule.text[config.start():config.end()] 
相關問題