我需要从外部文件中加载一些必须执行的正则表达式.
算法不需要知道它们是什么样的正则表达式.但最后它必须打印标签。
email_re=["EMAIL","([^@|\s]+@[^@]+\.[^@|\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数组定义外部文本文件中的所有regex的最佳方法是什么?
发布于 2015-03-13 13:31:36
使用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 printjson文件:
{
"email" : "([^@|\\s]+@[^@]+\\.[^@|\\s]+)",
"phone" : "(\\d{3}[-\\.\\s]??\\d{3}[-\\.\\s]??\\d{4}|\\(\\d{3}\\)\\s*\\d{3}[-\\.\\s]??\\d{4}|\\d{3}[-\\.\\s]??\\d{4})"
}https://stackoverflow.com/questions/29033262
复制相似问题