Python 字符串提取月份:正则表达式方法
使用 Python 编程,获取一个字符串里面的月份内容:你可以使用正则表达式来提取一个字符串中的月份。以下是一个使用 Python 的示例代码:
import re
def get_months_from_string(string):
# 正则表达式模式,匹配月份的字符串
pattern = r'[Jj]an(?:uary)?|[Ff]eb(?:ruary)?|[Mm]ar(?:ch)?|[Aa]pr(?:il)?|[Mm]ay|[Jj]un(?:e)?|[Jj]ul(?:y)?|[Aa]ug(?:ust)?|[Ss]ep(?:tember)?|[Oo]ct(?:ober)?|[Nn]ov(?:ember)?|[Dd]ec(?:ember)?'
# 使用正则表达式搜索匹配的月份
matches = re.findall(pattern, string)
return matches
# 测试示例
string = 'Today is the 1st of January, and tomorrow will be the 2nd of February.'
months = get_months_from_string(string)
print(months)
输出结果为:['January', 'February']
原文地址: http://www.cveoy.top/t/topic/nnG7 著作权归作者所有。请勿转载和采集!