首页 > 解决方案 > 正则表达式提取从和到日期?

问题描述

我正在尝试使用正则表达式从单独的组中提取和提取年份,但由于格式不同而无法提取,如下所示。应用正则表达式:([0-9]+)-?([0-9a-z]+)

以下是需要提取的完整数据:

['165-180 A.D.',
 '1520-unknown',
 '1665',
 '1817-1923',
 'Late 1800s',
 '1918-1920',
 '1957-1958',
 '2009']

上面的正则表达式提取165,1520,166在组1和2019,unknown, 5组2。需要把1665放在group1和group2正则表达式中的空白字段。同样,group1 中的 1800 年代后期

wp_page = requests.get("https://www.washingtonpost.com/graphics/2020/local/retropolis/coronavirus-deadliest-pandemics/")
wp_soup = bs(wp_page.content, 'html.parser')

[names.get_text() for  names in wp_soup.find_all('h5')][0:-2]

wp_year_from_list=[]
wp_year_to_list=[]
wp_year_regex=re.compile('([0-9]+)-?([0-9a-z]+)')
for names in wp_soup.find_all('h5'):
    if (wp_year_regex.search(names.text)!= None):
        wp_year_from_list.append(wp_year_regex.search(names.text).group(1))
        wp_year_to_list.append(wp_year_regex.search(names.text).group(2))```

标签: pythonpython-3.xregexweb-scrapinglist-comprehension

解决方案


根据您的要求,您需要?为第二组添加量词。所以你的正则表达式看起来像:

([0-9]+)-?([0-9a-z]+)?
                     ^^

上述正则表达式的解释

([0-9]+)- 捕获数字 1 次或更多时间的捕获组。

-?- 匹配连字符字面上的零次或 1 次。

([0-9a-z]+)?- 第二个捕获组捕获数字和字母1次或多次,该组可以出现0次或1次。

在此处输入图像描述

您可以在此处找到上述正则表达式的演示。


推荐阅读