【问题标题】:Removing Rows based on duplicate keywords using Regex使用正则表达式删除基于重复关键字的行
【发布时间】:2014-10-15 14:10:15
【问题描述】:

我正在寻找有关如何删除具有重复关键字或 IP 地址的行的答案。例如。

169.146.25.111 1412969662.95 This is just to make it unique
169.146.25.111 1412969662.95 This data doesn't matter
169.146.25.111 1712515362.95 This is all different
169.146.25.112 1412969662.95 Don't care what's here
169.146.25.111 1315125152.95 erroneous information

所以我希望它匹配 IP 地址,然后搜索以下行,如果它在行首找到 IP 地址,则删除该行。这是我一直在尝试使用的。

Find what:
^(\S+)(.*?)$\s+(?=.*^\1).*?$
Replace With:
\1\2

想要的结果

169.146.25.111 1412969662.95 This is just to make it unique
169.146.25.112 1412969662.95 Don't care what's here

我正在寻找正则表达式的答案。我知道它可以很容易地用 sort 或 awk 完成,但我一直在努力让它与 Regex 一起工作,它伤害了我的大脑。谢谢

【问题讨论】:

  • 这里的目的是保留第一行并删除重复的行吗?还是删除重复的行并保留最后一行?
  • 我有一个包含一大堆 IP 地址的文件,我只需要保留具有唯一 IP 地址的数据行。所以我想删除具有重复 IP 地址的行,即使该行的其余部分不是重复的。

标签: regex notepad++


【解决方案1】:

IP地址示例,全局搜索和空替换字符串(dotall选项必须取消选中)

^(\S++).*\R(?=(?>.*\R)*?\1 )

图案说明:

^              # start of the line anchor
(\S++)         # captures all non whitespace characters 
               # the possessive quantifier '++' forbids backtracking
.*             # all until the newline character (dotall mode disable)
\R             # a newline (whatever the system \r, \r\n, \n)
(?=            # open a lookahead test
    (?>        # open an atomic group (forbids backtracking once closed)
        .*\R   # a line (with the next newline)
    )*?        # the atomic group may occur zero or more times
    \1         # backreference to the capture group
)              # close the lookahead

【讨论】:

  • 这很好用,谢谢你,现在重要的部分是让我调整它并弄清楚它为什么起作用,即使你的描述性 cmets 我还是有点模糊。感谢您的快速响应,再次感谢您。
【解决方案2】:

基于 OP 的示例模式和提供的数据,仅适用于连续行

^(\S++)(.*)(?:\R\1.*)+

并替换为\1\2,dotall 选项也必须取消选中
Demo

【讨论】:

    猜你喜欢
    • 2011-06-02
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多