python中正则表达式匹配年份,用于提取月份和年份的Python正则表达式

I want to extract month and year from string. For example:

If I have a string From August 2017 - September 2018 then I should get 'August 2017' and 'September 2018' as two groups. I tried the following:

import re

regex = r'(\b\d{1,2}\D{0,3}\b-)?\b(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(Nov|Dec)(?:ember)?)\D?(\d{1,2}\D?)?\D?((19[7-9]\d|20\d{2})|\d{2})'

experience = re.findall(regex, 'August 2017 - Sep 2018')

print(experience)

This returns [('', '', '20', '17', ''), ('', '', '20', '18', '')]

I also tried re.search:

import re

regex = r'(\b\d{1,2}\D{0,3}\b-)?\b(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(Nov|Dec)(?:ember)?)\D?(\d{1,2}\D?)?\D?((19[7-9]\d|20\d{2})|\d{2})'

experience = re.search(regex, 'August 2017 - Sep 2018')

print(experience.group())

This returns only August 2017

Can we have some regex to extract both the dates?

解决方案

Do you mean like this? Regex demo.

import re

string = "From August 2017 - September 2018"

month = re.search("(?P\w+.\d+)\s+\-\s+(?P\w+.\d+)", string)

month = month.groups()

print (month)

Output:

('August 2017', 'September 2018')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值