-4

我将如何过滤掉包含某个字符串的文件:

假设我正在使用以下正则表达式过滤文件路径

"/.xml$|.json$/i"

我想忽略 xml 但_unwanted_string名称中包含的文件

例如:

file_name_unwanted_string.xml

SOMEOTHERNAME_unwanted_string.xml

NAME3_unwanted_string.xml

NAME3_unwanted_string_MORE_TEXT.xml

应该都被正则表达式所捕获。

这可以用正则表达式吗?

4

1 回答 1

-2

关于所使用的环境,这个问题非常不完整。
假设您可以访问 python 控制台,您可以运行如下内容:

import re
import os

l = ( "file_name_unwanted_string.xml",
       "SOMEOTHERNAME_unwanted_string.xml",
       "NAME3_unwanted_string.xml",
       "NAME3_unwanted_string_MORE_TEXT.xml",
       "good_file.xml",
       "bad_unwanted_string_good.xml",
)
# or, assuming the current directory has the files you are interested in
# l = os.listdir()

[i for i in l if not re.search(r"(?=_unwanted_string)(.+)[.]xml$", i)] 

>>> ['good_file.xml']

l你当然可以改变os.listdir

于 2021-03-03T14:54:56.307 回答