gpt4 book ai didi

Python 的 re.split() 没有删除所有匹配的字符

转载 作者:太空宇宙 更新时间:2023-11-03 11:17:20 25 4
gpt4 key购买 nike

这简直让我抓狂。我确信正则表达式匹配字符串开头的整个日期范围。然而,当我执行 re.split 时,一个 8 卡在后面。这是怎么回事,我如何在该日期范围内拆分(在某些情况下,它可能在字符串的开头和中间,因此拆分)?

import re
a = "09/05/2018-12/18/2018 Lecture Wednesday 01:30PM - 02:45PM, Room to be Announced"
b = r"([0-9]|\/|-){21}"
print re.split(b, a)

结果

['', '8', ' Lecture Wednesday 01:30PM - 02:45PM, Room to be Announced']

最佳答案

来自 re.split 的文档:

If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list.

您确实有一个捕获组,它最后匹配的是字符 8。这就是返回 8 的原因。

您可以改用非捕获组:

>>> b = r"(?:[0-9]|\/|-){21}"
^^ note these two characters added
>>> re.split(b, a)
['', ' Lecture Wednesday 01:30PM - 02:45PM, Room to be Announced']

或者您可以将所有选择放在一个字符类中,根本不需要一个组:

>>> b = r"[-/0-9]{21}"
>>> re.split(b, a)
['', ' Lecture Wednesday 01:30PM - 02:45PM, Room to be Announced']

关于Python 的 re.split() 没有删除所有匹配的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49583535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com