1

我有一个简单的函数,它应该根据模式输出前缀,或者None如果它不匹配。尝试做海象似乎不起作用。任何想法?

import re

def get_prefix(name):
    if m := re.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$', name) is not None:
        return m.group(3) + m.group(2) + m.group(1)

get_prefix('abc 10-12-2020')

追溯

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in get_prefix
AttributeError: 'bool' object has no attribute 'group'
4

1 回答 1

3

您设置mre.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$', name) is not None,这是一个布尔值。

你大概是说

if (m := re.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$', name)) is not None:

但无论如何你都不需要is not None这里。匹配是真的,无是假的。所以你只需要:

if m := re.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$', name):

(可以说,()在使用赋值表达式时最好使用,以明确分配的内容。)

请参阅PEP572#Relative 优先级 of :=

于 2021-05-12T10:39:05.923 回答