在python中执行位于外部文件中的regex

2024-04-19 16:37:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从外部文件加载一些必须执行的正则表达式。。。你知道吗

算法不需要知道它们是什么类型的正则表达式。。。但最后必须打印标签

    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的最佳方法是什么?你知道吗


Tags: 文件inre算法类型foremailmatch
1条回答
网友
1楼 · 发布于 2024-04-19 16:37:29

使用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]+@[^@]+\\.[^@|\\s]+)",
 "phone" : "(\\d{3}[-\\.\\s]??\\d{3}[-\\.\\s]??\\d{4}|\\(\\d{3}\\)\\s*\\d{3}[-\\.\\s]??\\d{4}|\\d{3}[-\\.\\s]??\\d{4})"
}

相关问题 更多 >