Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何编写排除某些文件后缀的正则表达式?_Python_Regex_Regex Lookarounds - Fatal编程技术网

Python 如何编写排除某些文件后缀的正则表达式?

Python 如何编写排除某些文件后缀的正则表达式?,python,regex,regex-lookarounds,Python,Regex,Regex Lookarounds,我正在看这里给出的教程:- 我想排除以.pqr.gz结尾的文件,但我不太确定如何做到这一点 e、 例如,预期的行为是:- f1.gz => succeed f1.abc.pqr => succeed f1.pqr.gz => fail f1.abc.gz => succeed 我能想到的最好的正则表达式是:- r'.*[.](?=[^.]*[.][^.]*)(?!pqr[.]gz$)[^.]*[.][^.]*$' 这排除了以.pqr.gz结尾的文件,但不允许仅为f1

我正在看这里给出的教程:-

我想排除以.pqr.gz结尾的文件,但我不太确定如何做到这一点

e、 例如,预期的行为是:-

f1.gz => succeed
f1.abc.pqr => succeed
f1.pqr.gz => fail
f1.abc.gz => succeed
我能想到的最好的正则表达式是:-

r'.*[.](?=[^.]*[.][^.]*)(?!pqr[.]gz$)[^.]*[.][^.]*$'
这排除了以.pqr.gz结尾的文件,但不允许仅为f1.gz的文件(即我上面写的第一个案例)

关于如何改进这一点有什么想法吗


编辑:-有更好的方法可以做到这一点(例如,使用
string.endswith
),但我很好奇如何使用正则表达式来实现这一点,这纯粹是一种练习。

好吧,TBH,你对正则表达式的使用对我来说似乎有些过头了。你可以简单地做:

if not '.pqr.gz' in line:
    print(line)
完成了

实际上,“简单”字符串操作只需几个简单的操作即可完成很多操作,例如:

for line in lines:
    file, result = line.split(' => ')
    if file.endswith('.pqr.gz'):
        print("Skipping file {}".format(file), file=sys.stderr)
        continue
    print(file)
    # and you could do something if result == "success" there after!

当您坚持使用regexps时:

这是您当前的正则表达式

以下是一个从@rawing suggestion中得到启发的解决方案:

.*(?<!\.pqr\.gz) =>
*(?

Python的
re
模块需要注意的一点是
re.match
隐式地锚定到字符串的开头

此外,您还可以通过转义文字句点(
\.
)来匹配文字句点,这可能比将其放入字符类更容易阅读(而且可能更快)

对于
re.match
来说,下面的正则表达式应该可以做到这一点:

r'.*\.pqr\.gz$'
如果改用
re.search
,正则表达式可以缩短为:

r'\.pqr\.gz$'

你不应该用正则表达式来检查后缀。
*(?@Rawing)这很有效。你能把它写下来作为一个答案(希望有一个解释)吗?我会接受的。我想我应该提到的是,在使用正则表达式时,这更多的是一种心理练习,而不是出于任何实际目的。但是你想过滤掉不是gz或pqr的扩展,对吗?(太糟糕了,图像链接已经死了……debuggex怎么了?☹)使用re.match需要注意的另一件事是,您必须在字符串的末尾提供自己的锚点。有两种选择,
\Z
$
$
是perl的遗留问题。再次使用
\Z
\Z
只有当您明确希望考虑尾随的换行时才更可取通过match语句。
$
不仅仅是perl的宿醉,它是另一个也很有用的锚。例如,如果您试图匹配一行的结尾而不是字符串的结尾,特别是在使用
标志=re.MULTILINE
时,
\Z
是错误的选择。再次看看OP的问题…想要str吗以“foo”而不是“foo”结尾的字符串\n