正则表达式在某些特定单词后提取日期

2024-05-19 02:12:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从这些文字中提取出生日期。有四个条件:

keywords to match 

    Date of Birth 
    date of birth:
    D.O.B:
    DOB:

像这样的字符串:

text = "my name is adam my DOB: 30-11-1988 and i play football since 20-2011"
text = "my name is D.O.B: 20/MAY/1987 and i play football since 20-2011"
text = "my Date of Birth 12-7-1970 and i start study since 20-2011"
text = "my date of birth: 20/9/1970 "

Tags: andoftextnameplaydateismy
2条回答

你可以这样做:

regex = r'(Date of Birth|date of birth|D.O.B|DOB):\s(\S*)'

您的第2组将包含任何格式的捕获日期

现场演示here

解释

  • (Date of Birth|date of birth|D.O.B|DOB):寻找dob短语的任何替代词
  • :\s:查找后跟空格字符的冒号
  • (\S*):查找任意数量的连续非空格字符,这是您想要的日期
(DOB: \d{1,2}-\d{1,2}-\d{1,4}|D.O.B: \d{1,2}\/[A-Z]{1,}\/\d{1,4}|Date of Birth \d{1,2}-\d{1,2}-\d{1,4}|date of birth: \d{1,2}\/\d{1,2}\/\d{1,4})
  • \d:表示所有数字,即[0-9]
  • {1,2}:长度,即最少1个或最多2个字符
  • [A-Z]:允许A-Z所有字母

希望对你有用

相关问题 更多 >

    热门问题