regex - 在 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”之后的出生日期。想知道我该怎么做?谢谢你。
解决方案
您可以使用(?<=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']
推荐阅读
- c - 理解不同C指针赋值的区别
- angular - 为排序标题事件角材质创建模拟
- bixby - “表单”和“布局”可以一起用于渲染输入视图吗?
- vue.js - 如何将 CodePen 拆分为 webpacked 组件?
- react-navigation - 从 React-Navigation V4 - V5 迁移 CommonActions.init 和 router.getStateForAction 发生了什么?
- protractor - 量角器的 multiCapabilities 使用相同类型的浏览器是否被认为是一个孤立的环境?
- iis - 在 IIS 中设置 ETag 的问题
- sql - sql查询显示那些为0的
- javascript - 在 Javascript 或 jQuery 中如何滚动以使另一个 div 内的元素垂直和水平居中
- html - 使用 Shiny 链接到 RMarkdown 上的本地 html 文件