Python Regex匹配任何内容

2024-04-25 07:23:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让我的正则表达式正常工作,但不知道我做错了什么。我试图找到任何不是特定格式的文件。例如,所有文件都是采用这种格式MM-DD的日期-YY.pdf(例如05-13-17.pdf)。我希望能够找到任何不是以这种格式编写的文件。在

我可以创建一个正则表达式来查找那些具有:

(\d\d-\d\d-\d\d\.pdf)

我试着用消极展望法,结果是这样的:

^{pr2}$

这样就不会再找到那些文件了,但它找不到与它不一样的文件。在

我还试着在组后面加一个*号,但那会找到整个列表。在

(?!\d\d-\d\d-\d\d\.pdf).*

我正在搜索一个小的测试列表:

05-17-17.pdf Test.pdf 05-48-2017.pdf 03-14-17.pdf

有什么方法可以完成我想要的吗?在

谢谢!在


Tags: 文件方法test列表pdf格式ddmm
2条回答

你可以试试这个:

import re
s = "Test.docx 04-05-2017.docx 04-04-17.pdf secondtest.pdf"

new_data = re.findall("[a-zA-Z]+\.[a-zA-Z]+|\d{1,}-\d{1,}-\d{4}\.[a-zA-Z]+", s)

输出:

^{pr2}$

首先找到所有匹配的,然后分别从列表中删除它们。firstFindtheMatching方法首先使用re库查找匹配的名称:

def firstFindtheMatching(listoffiles):
    """
    :listoffiles: list is the name of the files to check if they match a format
    :final_string: any file that doesn't match the format 01-01-17.pdf (MM-DD-YY.pdf) is put in one str type output. (ALSO) I'm returning the listoffiles so in that you can see the whole output in one place but you really won't need that. 

    """
    import re
    matchednames = re.findall("\d{1,2}-\d{1,2}-\d{1,2}\.pdf", listoffiles)
    #connect all output in one string for simpler handling using sets
    final_string = ' '.join(matchednames)
    return(final_string, listoffiles)

输出如下:

^{pr2}$

如果你想重新生成结果,我用了下面的主函数。这样做的好处是可以向firstFindtheMatching()添加更多的regex。它能帮助你把事情分开。在

def main():

    filenames= "05-08-17.pdf Test.pdf 04-08-17.pdf 08-09-16.pdf 08-09-2016.pdf some-all-letters.pdf"
    [matchednames , alllist] = firstFindtheMatching(filenames)
    print(matchednames, alllist)
    notcommon = set(filenames.split()) - set(matchednames.split())
    print(notcommon)




if __name__ == '__main__':
    main()

相关问题 更多 >