<p>请注意,将同样在字符串中的同一位置匹配的长模式连接起来是一个非常糟糕的主意。这将导致regex引擎回溯太多,并可能导致崩溃和减速。如果有一种方法可以重写替换项,使它们只能在不同的位置匹配,甚至可以完全删除它们,那么就这样做吧。你知道吗</p>
<p>此外,应该使用分组构造<code>(...)</code>对模式序列进行分组,并且在需要匹配特定字符时只使用<code>[...]</code>字符类。你知道吗</p>
<p>另外,你的选择是重叠的,你可以很容易地把它们结合起来。请参见固定正则表达式:</p>
<pre><code>\b(?<!\.)\d{1,2}(?:[/-]\d+[/-]|(?:th|st|[nr]d)?\s*(?:(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*))\s*(?:\d{4}|\d{2})\b
</code></pre>
<p>参见<a href="https://regex101.com/r/kSxCzi/3" rel="nofollow noreferrer">regex demo</a>。你知道吗</p>
<p><strong>细节</strong></p>
<ul>
<li><code>\b</code>-单词边界</li>
<li><code>(?<!\.)</code>-no<code>.</code>立即位于当前位置的左侧</li>
<li><code>\d{1,2}</code>-1或2位数字</li>
<li><code>(?:</code>-非捕获交替组的开始:
<ul>
<li><code>[/-]\d+[/-]</code>-<code>/</code>或<code>-</code>,1+位,<code>-</code>或<code>/</code></li>
<li><code>|</code>-或</li>
<li><code>(?:th|st|[nr]d)?\s*(?:
(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*))</code>-<code>th</code>、<code>st</code>、<code>nd</code>或<code>rd</code>(可选),后跟0+空格,然后是月份名称</li>
</ul></li>
<li><code>\s*</code>-0+空格</li>
<li><code>(?:\d{4}|\d{2})</code>-2或4位数字</li>
<li><code>\b</code>-尾随词边界。你知道吗</li>
</ul>
<p>另一个注意:如果您想用两个匹配的分隔符来匹配类似日期的字符串,则需要捕获第一个分隔符,并使用backreference来匹配第二个分隔符,请参见<a href="https://regex101.com/r/WVbdNo/1" rel="nofollow noreferrer">this regex demo</a>。在Python中,需要一个<code>re.finditer</code>来获得这些匹配。你知道吗</p>
<p>见<a href="https://ideone.com/muHQ31" rel="nofollow noreferrer">this Python demo</a>:</p>
<pre><code>import re
rx = r"\b(?<!\.)\d{1,2}(?:([/-])\d+\1|(?:th|st|[nr]d)?\s*(?:(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*))\s*(?:\d{4}|\d{4})\b"
s = "Lithium 0.25 (7/11/77). LFTS wnl. Urine tox neg. Serum tox\nfluoxetine 500; otherwise neg. TSH 3.28. BUN/Cr: 16/0.83. Lipids unremarkable. B12 363, Folate >20. CBC: 4.9/36/308 Pertinent Medical\nReview of Systems Constitutional:\n\nThe patient is a 44 year old married Caucasian woman, unemployed Decorator, living with husband and caring for two young children, who is referred by Capitol Hill Hospital PCP, Dr. Heather Zubia, for urgent evaluation/treatment till first visit with Dr. Toney Winkler IN EIGHT WEEKS on 24 Jan 2001"
print([x.group(0) for x in re.finditer(rx, s, re.I)])
# => ['7/11/77', '24 Jan 2001']
</code></pre>