简体   繁体   English

使用正则表达式检查文件扩展名

[英]Check file extensions with Regex

I am writing a script to change the name of the video file based on the subtitle files using regular expression. 我正在编写一个脚本,使用正则表达式根据字幕文件来更改视频文件的名称。

for files in curDir:
    if re.search(r'.*[.srt]$',files): #1
        print files;
    if re.search(r'.*[^.srt]$',files): #2
        print files;

During execution what I found was that the #1 if condition is executed continuously so that all the .srt files are printed then only #2 if condition is executed and all video files are printed. 在执行过程中,我发现#1 if条件连续执行,以便打印所有.srt文件,然后仅#2如果条件执行且所有视频文件都打印了。

Shouldn't those if conditions be executed alternately for each files like first #1 and then #2 ? 不应如果那些条件来交替地针对每个被执行files状的第一#1 ,然后#2

I think my problem is the way in which the re.search returns results. 我认为我的问题是re.search返回结果的方式。 So, I need help to access the if conditions one after another for each files. 因此,我需要帮助来依次访问每个文件的if条件。

You do not need Regex to check whether or not the filenames end in .srt . 您不需要Regex来检查文件名是否以.srt结尾。 str.endswith will do this easily: str.endswith将很容易做到这一点:

for files in curDir:
    if files.endswith('.srt'):  # Filename ends in .srt
        ...
    else:                       # Filename does not end in .srt
        ...

Regex should only be used when you have complex patterns to match (and then, by all means, use it!). 仅当您有复杂的模式要匹配时才使用正则表达式(然后,一定要使用它!)。 Otherwise, it should be avoided because it is slower than Python's built-in tools and also somewhat difficult for people who are not experienced with it. 否则,应避免使用它,因为它比Python的内置工具慢,并且对不熟悉它的人也有些困难。

sorry I can not comment to existing answers yet. 抱歉,我无法评论现有答案。 just want to point out that it'd be better to use what's in the chosen answer with tiny modification: 只想指出,最好使用经过微小修改的选定答案中的内容:

for file in curDir:
    if file.lower().endswith('.srt'):  # Filename ends in .srt
        ...
    else:                       # Filename does not end in .srt
        ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM