Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将.htm或.html扩展与python RE匹配_Python_Html_Regex_File_Expression - Fatal编程技术网

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

将.htm或.html扩展与python RE匹配,python,html,regex,file,expression,Python,Html,Regex,File,Expression,正如标题中提到的,我需要匹配Python中的.htm或.html文件扩展名。 我尝试使用标准库中的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) 和其他变体,但都

正如标题中提到的,我需要匹配Python中的.htm或.html文件扩展名。 我尝试使用标准库中的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)
和其他变体,但都不起作用。 问题是,这些模式识别出像.html或类似的文件扩展名,我不想要它们(只有htm和html)

有人能帮我找到正确的模式吗?
谢谢大家

您只需要
重新搜索('\.html?$',文件)
。括号用于创建捕获组,您不希望在此处执行此操作

我还将提到一个更复杂的替代解决方案,因为您似乎正在尝试这样做:
re.search('\.(?:(?:html)|(?:htm))$,file)
。这将完成与上述正则表达式相同的任务,但要长得多,复杂得多


最后,如果您还想获取文件名,请执行
re.search('^.*.\.html?$',file)

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

我还将提到一个更复杂的替代解决方案,因为您似乎正在尝试这样做:
re.search('\.(?:(?:html)|(?:htm))$,file)
。这将完成与上述正则表达式相同的任务,但要长得多,复杂得多


最后,如果您还想获取文件名,请执行
re.search('^.*.\.html?$',file)

在这种情况下不需要正则表达式,请改用,即:

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

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

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

您需要在url或本地文件上匹配文件扩展名?@Pedro他们在我的电脑上。您只需要检查文件扩展名是否匹配或是否需要捕获匹配?您需要在url或本地文件上匹配文件扩展名?@Pedro他们在我的电脑上。您只需要检查文件扩展名是否匹配或是否需要捕获匹配?以及如果文件名为
test.htmlimage.jpg
?最好将
$
放在正则表达式的末尾。@pzp不能正常工作。对于expample,它也匹配.htmk文件。@PedroLobito很好地捕捉到了。现在已修复。如果文件名为
test.htmlimage.jpg
?最好将
$
放在正则表达式的末尾。@pzp不能正常工作。对于expample,它也匹配.htmk文件。@PedroLobito很好地捕捉到了。现在修好了。