0

我正在编写一个简短的脚本来清理文件夹和文件名以上传到 SharePoint。由于 SharePoint 很挑剔,并且除了简单的不允许字符之外还有一些文件名规则(例如,不允许多个连续的句点),因此似乎正则表达式是要走的路,而不是简单地替换单个字符。然而,一种似乎不起作用的表达式是:

[/<>*?|:"~#%&{}\\]+

作为一个简单的字符类匹配,我希望它可以正常工作,并且它似乎在记事本++中这样做。我的期望是这样的字符串

St\r/|ng

使用上述正则表达式将匹配 \、/ 和 |。然而,无论我做什么,我只能让字符串匹配第一个反斜杠,或者它遇到的那个类中的任何字符的第一个。这是通过 Python re 库完成的。有谁知道这里的问题是什么?导入 os、sys、shutil、re

def cleanPath(path):
    #Compiling regex...
    multi_dot = re.compile(r"[\.]{2,}")
    start_dot = re.compile(r"^[\.]")
    end_dot = re.compile(r"[\.]$")
    disallowed_chars = re.compile(r'[/<>*?|:"~#%&{}\\]+')
    dis1 = re.compile(r'\.files$')
    dis2 = re.compile(r'_files$')
    dis3 = re.compile(r'-Dateien$')
    dis4 = re.compile(r'_fichiers$')
    dis5 = re.compile(r'_bestanden$')
    dis5 = re.compile(r'_file$')
    dis6 = re.compile(r'_archivos$')
    dis7 = re.compile(r'-filer$')
    dis8 = re.compile(r'_tiedostot$')
    dis9 = re.compile(r'_pliki$')
    dis10 = re.compile(r'_soubory$')
    dis11 = re.compile(r'_elemei$')
    dis12 = re.compile(r'_ficheiros$')
    dis13 = re.compile(r'_arquivos$')
    dis14 = re.compile(r'_dosyalar$')
    dis15 = re.compile(r'_datoteke$')
    dis16 = re.compile(r'_fitxers$')
    dis17 = re.compile(r'_failid$')
    dis18 = re.compile(r'_fails$')
    dis19 = re.compile(r'_bylos$')
    dis20 = re.compile(r'_fajlovi$')
    dis21 = re.compile(r'_fitxategiak$')
    regxlist = [multi_dot,start_dot,end_dot,disallowed_chars,dis1,dis2,dis3,dis4,dis5,dis5,dis6,dis7,dis8,dis9,dis10,dis11,dis12,dis13,dis14,dis15,dis16,dis17,dis18,dis19,dis20,dis21]
    print("************************************\n\n"+path+"\n\n************************************\n")
    for x in regxlist:
        match = x.search(path)
        if match:
            print("\n")
            print("MATCHED")
            print(match.group())

    print("___________________________________________________________________________")
    return path


#testlist of conditions that should be found, some OK, some bad
testlist = ["string","str....ing","str..ing","str.ing",".string","string.",".string.","$tring",r"st\r\ing","st/r/ing",r"st\r/|ng","/str<i>ng","str.filesing","string.files"]
testlist_ans = ["OK","Match ....","Match ..","OK","Match .","Match .","Match . .","OK",r"Match \ ","Match /",r"Match \/|","Match / < >","OK","Match .files"]
count = 0
for i in testlist:
    print(testlist_ans[count])
    count = count + 1

    cleanPath(i)
4

2 回答 2

1
re.sub(pattern,new_txt,subject) #replace all instinces of pattern with new_txt
re.findall(pattern,subject) #find all instances
于 2012-09-12T15:00:03.207 回答
1

你使用什么 Python re 命令?

你应该使用:re.findall

于 2012-09-12T15:05:26.337 回答