如何在python中将多个正则表达式组合成一个? [英] How to combine multiple regex into single one in python?

查看:209
本文介绍了如何在python中将多个正则表达式组合成一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习正则表达式.我不知道如何将不同的正则表达式组合成一个通用的正则表达式.

I'm learning about regular expression. I don't know how to combine different regular expression to make a single generic regular expression.

我想编写一个适用于多种情况的正则表达式.我知道这可以通过使用 " | " 运算符以天真的方法完成.

I want to write a single regular expression which works for multiple cases. I know this is can be done with naive approach by using or " | " operator.

我不喜欢这种方法.有人能告诉我更好的方法吗?

I don't like this approach. Can anybody tell me better approach?

推荐答案

您需要编译所有正则表达式函数.检查这个例子:

You need to compile all your regex functions. Check this example:

import re
re1 = r'\d+\.\d*[L][-]\d*\s[A-Z]*[/]\d*'
re2 = '\d*[/]\d*[A-Z]*\d*\s[A-Z]*\d*[A-Z]*'
re3 = '[A-Z]*\d+[/]\d+[A-Z]\d+'
re4 = '\d+[/]\d+[A-Z]*\d+\s\d+[A-z]\s[A-Z]*'

sentences = [string1, string2, string3, string4]
for sentence in sentences:
    generic_re = re.compile("(%s|%s|%s|%s)" % (re1, re2, re3, re4)).findall(sentence)

这篇关于如何在python中将多个正则表达式组合成一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆