gpt4 book ai didi

python - 正则表达式点不起作用

转载 作者:太空狗 更新时间:2023-10-30 02:41:16 25 4
gpt4 key购买 nike

所以我试图解析一个文件,我有以下代码:

def learn_re(s):
pattern=re.compile("[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3} .")
if pattern.match(s):
return True
return False

这与“01:01:01.123 —”匹配;但是,当我再添加一个字符时,它就无法工作了。例如,如果我编辑我的代码,使其成为

def learn_re(s):
pattern=re.compile("[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3} . C")
if pattern.match(s):
return True
return False

这与“01:01:01.123 — C”不匹配这里发生了什么?

最佳答案

问题是您的 — 是一个 unicode 字符。在 str 中时,它实际上表现得更像几个字符:

>>> print len('—')
3

但是,如果您使用 unicode 而不是 str:

>>> print len(u'—')
1

因此,以下将打印 True:

def learn_re(s):
pattern=re.compile("[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3} . C")
if pattern.match(s):
return True
return False

print learn_re(u"01:01:01.123 — C")

请注意,此行为特定于 python 2。在 python 3 中,strunicode 合并为单个 str 类型,并且所以不需要这种区分。

关于python - 正则表达式点不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39861911/

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