英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论