简体   繁体   English

Python正则表达式模式

[英]Python Regular Expression pattern

I am renaming all of the files in a directory, and using a regex pattern to check if any of the files have a the appropriate file-name structure (I double checked the pattern on www.rubular.com, and it seemed to be correct). 我正在重命名目录中的所有文件,并使用正则表达式模式检查任何文件是否具有适当的文件名结构(我在www.rubular.com上仔细检查了该模式,这似乎是正确的)。 If so, it skips renaming he file. 如果是这样,它将跳过重命名他的文件。 The following code renames the file regardless if it has the appropriate file-name structure .... I'm not seeing why it does not skip over the file. 以下代码重命名该文件,无论它是否具有适当的文件名结构....我都不明白为什么它不跳过该文件。 Any help in determining why the regex pattern is not working will be appreciated: 在确定为什么正则表达式模式不起作用的任何帮助将不胜感激:

# Appropriate file name: P.002-night.jpg; File name to rename: bird.jpg


import os, os.path
import re


def displaymatch(match):
    if match is None:
        return None
    return '<Match: %r, groups=%r>' % (match.group(), match.groups())

sampledir = "c:\\Users\\Name\\Desktop\\New folder"
os.chdir(sampledir)
FileList = os.listdir(os.getcwd())


num = 000

pattern = r"\w.\d{3}\-\w+.(jpg|Jpg|JPG)"


for filename in FileList:
    if displaymatch(re.match(pattern, filename)) != None:
        pass
    else:
        os.rename(filename, "P." + str("{0:0=3d}".format(num)) + "-" + filename)
        num+= 1
pattern = r"\w.\d{3}\-\w+.(jpg|Jpg|JPG)"


for filename in FileList:
    if displaymatch(re.match(pattern, filename)) is None:
        os.rename(filename, "P." + str("{0:0=3d}".format(num)) + "-" + filename)
        num+= 1

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

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