在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”之后的出生日期。想知道我该怎么办?谢谢。
您可以使用(?<=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']
您可以匹配DOB
并将捕获组用作日期部分。对于日期部分,天数和月数可以是可选的,然后可以匹配4位数字。
日期部分模式不验证日期本身,它使匹配更加具体。
\bDOB ((?:(?:3[01]|[12][0-9]|0?[1-9]) [A-Za-z]+ )?\d{4})\b
说明
\bDOB
匹配字面上的单词边界(
捕获组1(?:
非捕获组(?:3[01]|[12][0-9]|0?[1-9]) [A-Za-z]+
匹配数字1-31和1+字符A-Za-z)?
关闭组并使其可选]\d{4}
匹配4位数字)\b
关闭组1,然后加上单词边界例如:
import re
regex = r"\bDOB ((?:(?:3[01]|[12][0-9]|0?[1-9]) [A-Za-z]+ )?\d{4})\b"
test_str = ("DOB 23 Jun 1959; alt. DOB 23 Jun 1958\n"
"DOB 1959; alt. DOB 1958")
print(re.findall(regex, test_str))
输出
['23 Jun 1959', '23 Jun 1958', '1959', '1958']