使用列表作为python中正则表达式的参数

问题描述 投票:0回答:1

我正在构建正则表达式以在我的文本中查找日期。我创建了作为日期一部分的月份名称,日期和特殊字符的列表。

dict_month_name =['january','february','march','april','may','june','july','august','september','october','november','december']

dict_day =['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']

dict_special_char = ['-', '/', '.', ',' ,'',' ']

我也编译了它们,如下所示。

month_name = re.compile('|'.join(dict_month_name))

day = re.compile('|'.join(dict_day))

special_char = re.compile('|'.join(dict_special_char))

现在,在我下面显示的正则表达式中,我想使用我之前创建的列表的不同变体。对于例如搜索日期,如2017年1月1日,正则表达式将是 -

regexp1 = re.findall('.*?^(day+,\s,month_name+\s[0-9][0-9][0-9][0-9])$.*', text)

但是,正则表达式不会返回任何输出。我需要使用正则表达式而不是日期时间模块来解决这个问题。有没有办法可以将我的列表包含在正则表达式中,如上所示?

regex python-2.7
1个回答
1
投票

您可以通过以下方式组合正则表达式:

import re
dict_month_name =['january','february','march','april','may','june','july','august','september','october','november','december']
dict_day =['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
dict_special_char = ['-', '/', '.', ',' ,'',' ']

s = 'For e.g. to search for dates like - Monday, January 2017 the regex would be'
rx = r"\b(?:{day})[{special}]\s+(?:{month_name})\s+[0-9]{{4}}\b".format(
    day="|".join(dict_day), 
    special="".join([re.escape(x) for x in dict_special_char]), 
    month_name="|".join(dict_month_name))

print(re.findall(rx, s, re.I)) # => ['Monday, January 2017']

Python demo

在这个例子中,正则表达式将是

\b(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)[\-\/\.\,\ ]\s+(?:january|february|march|april|may|june|july|august|september|october|november|december)\s+[0-9]{4}\b

你看到模式现在是更大模式的一部分。 re.I支持不区分大小写的匹配。

另请注意,应使用[re.escape(x) for x in dict_special_char]转义特殊字符,以便与字面字符匹配。

© www.soinside.com 2019 - 2024. All rights reserved.