如何在Python中使用re匹配文件扩展名?

huangapple go评论57阅读模式
英文:

How does one match the file extension using re in python?

问题

我想匹配任何扩展名为 .Mp4 的文件。代码似乎不像我想象的那样工作...有什么线索吗?

import re

ext = r"\.Mp4$"
files = ["Good cool music yes.Mp4", "Very cool audio.mp3", "Top of the toppest.Mp4"]

for f in files:
    if re.match(ext, f): 
        print(f)
    else:
        pass
英文:

I would like to match any file with .Mp4 extension. The code does not seem to work as I thought...Any leads??

import re

ext=r"\.Mp4$"
files = ["Good cool music yes.Mp4", "Very cool audio.mp3", "Top of the toppest.Mp4"]


for f in files:
    if re.match(ext, f): 
        print(f)
    else:
        pass

答案1

得分: 1

我看到你正在使用re.match(),它仅检查字符串开头的匹配,而不管你传递的'$'标志如何。有关搜索与匹配的更多信息,请参阅https://docs.python.org/3/library/re.html#search-vs-match。

将你的代码更改为搜索将返回预期的结果:

import re

ext = r"\.mp4$"
files = ["Good cool music yes.Mp4", "Very cool audio.mp3", "Top of the toppest.Mp4"]

for f in files:
    if re.search(ext, f, flags=re.I): 
        print(f)
    else:
        pass
英文:

I can see is that you are using re.match() which only checks the beginning of the string for matches regardless of the '$' flag you were passing. See https://docs.python.org/3/library/re.html#search-vs-match for more info on search vs match.

Changing your code to search returns the expected results:

import re

ext=r"\.mp4$"
files = ["Good cool music yes.Mp4", "Very cool audio.mp3", "Top of the toppest.Mp4"]


for f in files:
    if re.search(ext, f, flags=re.I): 
        print(f)
    else:
        pass

</details>



huangapple
  • 本文由 发表于 2023年6月13日 15:33:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76462624.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定