regex - 正则表达式检测和替换具有重复捕获组的行以删除 pip requirements.txt 文件中的重复包
问题描述
如果 python requirements.txt文件对于同一个包有不同的版本,则它是无效的,表示为下面的行(假定文件已排序):
agate==1.6.0
agate==1.7.0
我正在尝试编写一个正则表达式来检测重复的包(不是行,因为版本可能不同)。我的捕获组由 表示^([^=]+)==.+$
。删除重复行接近解决方案,因为它对最后一行使用后向引用,但我的后向引用仅适用于捕获组,而不适用于整行。
解决方案
检测这些字符串
(?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))
推荐阅读
- python - 创建一个简单的登录系统作为个人项目并在 python 中遇到一些 IO 问题
- javascript - 如何在 Python 中处理(Java-)脚本变量?
- java - 线程和缓冲区策略的问题:IllegalStateException: Component must have a valid peer
- python-3.x - Python3没有在网页上获得全文
- visual-studio - 从 VS 2017 升级到 VS 2019 时简化项目文件夹
- android - 修复未解决的参考:为导入 kotlinx.android.synthetic.main.activity_add_widget 合成?
- python-3.x - 如何使用 Pandas-matplotlib 绘制 Binance API 订单簿?
- javascript - 按钮单击时来自 html 的随机图像
- javascript - 服务器以 403 响应,但在网站刷新时工作
- c - 虽然循环在 C 中运行两次