首页 > 解决方案 > 正则表达式检测和替换具有重复捕获组的行以删除 pip requirements.txt 文件中的重复包

问题描述

如果 python requirements.txt文件对于同一个包有不同的版本,则它是无效的,表示为下面的行(假定文件已排序):

agate==1.6.0
agate==1.7.0

我正在尝试编写一个正则表达式来检测重复的包(不是行,因为版本可能不同)。我的捕获组由 表示^([^=]+)==.+$删除重复行接近解决方案,因为它对最后一行使用后向引用,但我的后向引用仅适用于捕获组,而不适用于整行。

标签: regexpiprequirements.txt

解决方案


检测这些字符串

(?sm)^([^=]+)==.*\n\1==

证明

解释

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))

推荐阅读