2015-03-13 21 views
0

我需要從外部文件加載時,需要執行一些正則表達式...執行位於外部文件的正則表達式在Python

該算法不需要知道他們是什麼樣的正則表達式的.. 。但最終它必須打印在標籤

email_re=["EMAIL","([^@|\s][email protected][^@]+\.[^@|\s]+)"]; 
    phone_re=["PHONE","(\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4})"]; 

    regexs=[email_re, 
      phone_re] 

    for regex in regexs: 
     #print regex 
     match = re.search(regex[1], prodotto) 
     if match: 
      print regex[0]+": "+match.group() 

什麼是創建regexs數組定義在外部文本文件中的所有正則表達式的最好方法?

+0

做方案需要知道,如果正則表達式是一個正則表達式的電子郵件或電話的正則表達式,等等? – 2015-03-13 13:21:19

+0

它必須打印正在執行的正則表達式的標籤 – 2015-03-13 13:23:04

+0

,您可以將json放入文件並將其加載到程序中。 {「email」:「email regex here」,...} – 2015-03-13 13:25:28

回答

1

使用JSON作爲外部文件,試試這個:

import json 

json_data=open('regex.json') 
data = json.load(json_data) 

for label, regex in data.items(): 
    print label 
    print regex # process your regex here instead print 

JSON文件:

{ 
"email" : "([^@|\\s][email protected][^@]+\\.[^@|\\s]+)", 
"phone" : "(\\d{3}[-\\.\\s]??\\d{3}[-\\.\\s]??\\d{4}|\\(\\d{3}\\)\\s*\\d{3}[-\\.\\s]??\\d{4}|\\d{3}[-\\.\\s]??\\d{4})" 
} 
+0

它的工作原理!非常感謝!這是我需要的! – 2015-03-13 14:35:04

+0

不客氣 – 2015-03-13 14:35:19