正则表达式删除与第一个字符串匹配的行?

标签 regex replace duplicates

我有一长串包含很多情况的行, 具有相同第一个单词(空格之前的第一个字符串)但其余部分不同的行。 我只需要保留一行具有唯一的第一个字符串。

john jane
john 123
john jim jane
jane john
jane 123
jane 456
jim
jim 1

要得到这个结果:

john jane
jane john
jim

因此,如果行中的第一个单词是匹配项,则删除除一行之外的所有单词。

我可以删除所有重复的行,但保留如上例所示的行,

^(.*)(\r?\n\1)+$

此正则表达式删除相同的行,与示例中不同。 是否有正则表达式或记事本宏来解决这个问题?

最佳答案

使用 Notepad++ (假设首字相同的行是连续的):

搜索:^(\S++).*\K(?:\R\1(?:\h.*|$))+
替换:无

demo

图案细节:

^             # start of the line
(\S++)        # the first "word" (all that isn't a whitespace) captured in group 1
.*            # all characters until the end of the line
\K            # remove characters matched before from the match result
(?:
    \R        # a newline
    \1        # reference to the capture group 1 (same first word)
    (?:
        \h.*  # a horizontal whitespace 
      |       # OR
        $     # the end of the line
    )
)+            # repeat one or more times

关于正则表达式删除与第一个字符串匹配的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38393614/

相关文章:

java - 正确的正则表达式模式是什么?

c# - 帮助我使用 RegExp 拆分字符串

search - 如何在 vi 搜索和替换中包含正斜杠

python - 从 GoogleAppEngine 模型中删除重复项?

duplicates - Prolog:如何在不改变元素顺序的情况下消除元素列表的重复项?

mysql - 如何标记 MySQL 中的重复条目?

javascript - 按提供的输入过滤值

r - 使用 R 有选择地删除遵循模式的字符

C 分配字符串时无法包含格式说明符

python - 将号码替换为其他号码