将 .htm 或 .html 扩展名与 python RE 匹配

Match .htm or .html extensions with python RE

如题所述,我需要在[=中匹配一个.htm.html文件扩展名28=]。 我尝试使用标准库中的 RE 模块,但找不到正确的模式。 我测试了几种模式,看起来更正确(对我来说)但没有工作的模式如下:

re.search("\.(htm|html)",file)
re.search("\.htm(l)",file)
re.search("\.htm(l?)",file)
re.search("\.htm(l*?)",file)
re.search("\.htm(l+?)",file)

和其他变体,但 none 有效。 问题是,这些模式识别文件扩展名,如 .html 或类似的,我不想要它们(只有 htm 和 html)。

谁能帮我找到正确的模式? 谢谢大家

你只需要re.search('\.html?$', file)。括号用于创建捕获组,您不想在此处执行此操作。

我还会提到一个更复杂的替代解决方案,因为您似乎正试图做这样的事情:re.search('\.(?:(?:html)|(?:htm))$', file)。这将完成与上述 RegEx 相同的事情,但更长更复杂。

最后,如果你也想获取文件名,那就re.search('^.*?\.html?$', file)

在这种情况下不需要正则表达式,而是使用 endswith(),即:

if filePath.lower().endswith(('.html', '.htm')):