正则表达式用于检测和替换具有重复捕获组的行,以删除 piprequirements.txt 文件中的重复包

标签 regex pip requirements.txt

一条 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/

相关文章:

regex - 在 bash 中,如何检查数组中字符串的部分内容?

mysql - 无法安装 MySQL-Connector 库

python - 安装包依赖项的最佳实践在 pypi 中不可用

python - 为什么要在Python的虚拟环境中创建requirements.txt文件?

centos - 安装 CKAN 错误 - 无法确定原因

javascript - 基于分隔符javascript正则表达式分割字符串

Java正则表达式删除字符 'i'和 ':'之间的所有内容

javascript正则表达式选择带引号的字符串但不转义引号

python - pip 10 和 apt : how to avoid "Cannot uninstall X" errors for distutils packages

python - 通过 pip 安装包时出现 find_package() 错误