我如何使用正则表达式

时间:2018-03-01 00:13:50

标签: python regex

pattern = r"(Mon|Tues|Wednes|Thurs|Fri)day, (February|March) [0-9]{2}, [0-9]{4}\s*Day [0-9]{1}"

line = """
Wednesday, February 28, 2018 
Day 4 3:00 Dismissal 
All Day 

Thursday, March 01, 2018 
Day 5 1:30PM Dismissal 
All Day 

Friday, March 02, 2018 
Day 6 3:00 Dismissal 
All Day 

Monday, March 05, 2018 
Day 1 1:30 Dismissal 
All Day 

Tuesday, March 06, 2018 
Day 2 3:00 Dismissal 
All Day 
Tuesday, March 06, 2018"""

result = re.findall(pattern, line)
print(result)

赢了。

1 个答案:

答案 0 :(得分:1)

如果您只想抓住钥匙,请将其分组:

pattern = r"((?:Mon|Tues|Wednes|Thurs|Fri)day), (February|March) ([0-9]{2}), ([0-9]{4})\s*Day ([0-9]{1})"

将获得:

[('Wednesday', 'February', '28', '2018', '4'), ('Thursday', 'March', '01', '2018', '5'), ('Friday', 'March', '02', '2018', '6'), ('Monday', 'March', '05', '2018', '1'), ('Tuesday', 'March', '06', '2018', '2')] 

如果你想捕捉整个匹配字符串,请不要对它进行分组,(例如@ekhumoro说在组之前使用?:):

pattern = r"(?:Mon|Tues|Wednes|Thurs|Fri)day, (?:February|March) [0-9]{2}, [0-9]{4}\s*Day [0-9]{1}"

将获得str的列表:

['Wednesday, February 28, 2018 \nDay 4', 'Thursday, March 01, 2018 \nDay 5', 'Friday, March 02, 2018 \nDay 6', 'Monday, March 05, 2018 \nDay 1', 'Tuesday, March 06, 2018 \nDay 2']