F字符串中的Python正则表达式?

目前,我有以下内容:

for child in root:
    if child.attrib['startDateTime'] == fr'2019-11-10T{test_time}:\d{{2}}':
        print('Found')

哪些不起作用。这里的目标是将日期时间字符串与我自己的字符串匹配,其中test_time的格式为'HH:MM',秒位数可以为00-60。

这是解决此类问题的正确方法吗?还是我最好转换为日期时间对象?

Z584036976 回答:F字符串中的Python正则表达式?

您可以将正则表达式放在f字符串中,但是需要使用re模块与之匹配,而不是==

if re.match(fr'2019-11-10T{test_time}:\d{{2}}',child.attrib['startDateTime']):
    print('Found')
,

这不是问题所在。字符串上的r前缀并不表示“ regex”,而是表示“原始”-即,反斜杠按字面意义使用。对于正则表达式,请使用re module。这是使用Pattern.match的示例:

import re

regex = fr'2019-11-10T{test_time}:\d{{2}}'
pattern = re.compile(regex)
for child in root:
    if pattern.match(child.attrib['startDateTime']):
        print('Found')
本文链接:https://www.f2er.com/3089581.html

大家都在问