我试图让我的正则表达式起作用,但无法弄清楚我做错了什么。我试图找到任何不是特定格式的文件。例如,所有文件都是这种格式的日期MM-DD-YY.pdf(例如05-13-17.pdf)。我希望能够找到任何未以该格式编写的文件。
我可以创建一个正则表达式来查找那些:
(\d\d-\d\d-\d\d\.pdf)
我尝试使用负向前瞻,所以它看起来像这样:
(?!\d\d-\d\d-\d\d\.pdf)
这不再能找到那些,但它找不到那些不喜欢它的文件。
我也尝试在群组之后添加。*然后找到整个列表。
(?!\d\d-\d\d-\d\d\.pdf).*
我现在正在搜索一个小清单进行测试:
05-17-17.pdf Test.pdf 05-48-2017.pdf 03-14-17.pdf
有没有办法完成我正在寻找的东西?
谢谢!
答案 0 :(得分:1)
你可以试试这个:
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)
输出:
['Test.docx', '04-05-2017.docx', 'secondtest.pdf']
答案 1 :(得分:0)
首先找到匹配的所有内容,然后分别从列表中删除它们。 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)
这是输出:
('05-08-17.pdf 04-08-17.pdf 08-09-16.pdf', '05-08-17.pdf Test.pdf 04-08-17.pdf 08-09-16.pdf 08-09-2016.pdf some-all-letters.pdf')
set(['08-09-2016.pdf', 'some-all-letters.pdf', 'Test.pdf'])
如果您想重新生成结果,我已使用下面的主要内容。这样做的好处是可以为firstFindtheMatching()
添加更多正则表达式。它可以帮助您将事物分开。
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()