一条 python requirements.txt如果同一包有不同版本,则文件无效,如下行所示(假定文件已排序):
agate==1.6.0
agate==1.7.0
我正在尝试编写一个正则表达式来检测重复的包(不是行,因为版本可能不同)。
我的捕获组由 ^([^=]+)==.+$
表示。 Removing duplicated lines接近解决方案,因为它对最后一行使用反向引用,但我的反向引用仅适用于捕获组,而不适用于整行。
最佳答案
检测这些字符串
(?sm)^([^=]+)==.*\n\1==
参见proof .
说明
NODE EXPLANATION
--------------------------------------------------------------------------------
^ the beginning of the line
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
[^=]+ any character except: '=' (1 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
== '=='
--------------------------------------------------------------------------------
.* any character (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
\n '\n' (newline)
--------------------------------------------------------------------------------
\1 what was matched by capture \1
--------------------------------------------------------------------------------
== '=='
Python:
import re
regex = r"^([^=]+)==.*\n\1=="
test_str = "agate==1.6.0\nagate==1.7.0"
containsDupe = bool(re.search(regex, test_str, re.MULTILINE | re.DOTALL))
关于正则表达式用于检测和替换具有重复捕获组的行,以删除 piprequirements.txt 文件中的重复包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63402478/