首页 > 解决方案 > 在 python 3 regex findall 中匹配多个 OR 条件

问题描述

在python 3中:

这是应监控个人资产的外国资产控制办公室列表

https://www.treasury.gov/ofac/downloads/sdn.csv

他们的很多出生数据(最后一列,逗号分隔)就像

DOB 23 Jun 1959; alt. DOB 23 Jun 1958

或者

DOB 1959; alt. DOB 1958

我正在尝试使用以下代码捕获关键字“DOB”和“alt.DOB”之后的所有生日:

   if len(x.split(';')) > 0:
        if len(re.findall('DOB (.*)', x.split(';')[0])) > 0:
            new = re.findall('DOB | alt. DOB (.*)', x.split(';')[0])[0]
            print(new)

            try:
                print(datetime.strptime(new, '%d %b %Y'))
                return datetime.strptime(new, '%d %b %Y')
            except:
                return None

但是代码仅在“DOB”之后获得出生日期,但不包括“alt. DOB”之后的出生日期。想知道我该怎么做?谢谢你。

标签: regexpython-3.xfindall

解决方案


您可以使用(?<=DOB\s)[\s[a-zA-Z0-9]+]*

   (?<=DOB\s)  = Negative look-behind assertion. This matches string (which is to its right) only if the string preceded by letters DOB followed by a space
   [\s[a-zA-Z0-9]+]* = Match space followed by letters of numbers multiple times

例子:

items=['DOB 23 Jun 1959; alt. DOB 23 Jun 1958', 'DOB 1959; alt. DOB 1958']
for item in items:
    print(re.findall(r'(?<=DOB\s)[\s[a-zA-Z0-9]+]*',item))

输出

['23 Jun 1959', '23 Jun 1958']
['1959', '1958']

推荐阅读