在python中使用正则表达式解析日期

2024-09-26 22:07:23 发布

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

我有以下文字

txt = 'Lithium 0.25 (7/11/77).  LFTS wnl.  Urine tox neg.  Serum tox + fluoxetine 500; otherwise neg.  TSH 3.28.  BUN/Cr: 16/0.83.  Lipids unremarkable.  B12 363, Folate >20.  CBC: 4.9/36/308 Pertinent Medical Review of Systems Constitutional:'

我想在上面的表达式中得到日期,我已经写了下面的表达式。你知道吗

re.findall(r'(?:[\d{1,2}]+)(?:[/-]\d{0,}[/-]\d{2,4})', txt)

如果执行上面的表达式,则显示以下输出

['7/11/77','9/36/308']

我不想“4.9/36/308”这个被包括在内,我该如何改变这个正则表达式。你知道吗

请帮忙。你知道吗


Tags: txttox表达式cr文字lithiumnegotherwise
1条回答
网友
1楼 · 发布于 2024-09-26 22:07:23

您可以将当前正则表达式修复为

\b(?<!\.)\d{1,2}[/-]\d+[/-]\d{2,4}\b

参见regex demo

\b将匹配单词边界,如果匹配的第一个数字前面有一个.,则(?<!\.)负查找将失败匹配。你知道吗

参见Python demo。你知道吗

请注意,如果您只需要获得一个有效日期的列表,那么稍后就必须使用non-regex method。你知道吗

相关问题 更多 >

    热门问题