如何使用RegEx删除文本中的非连续行? [英] How to delete nonconsecutive lines in text using RegEx?

查看:111
本文介绍了如何使用RegEx删除文本中的非连续行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

问题是:


  1. 只有单行字符串,如果一行中有空格将不起作用。

  2. 仅用于连续重复的行。

是否有解决方案(最好是正则表达式或宏)来删除包含空格的文本中的重复行,是不连续的?

解决方案

由于没有人有兴趣,我会发布我认为你需要的。


在包含空格的文本中删除重复的行,不连续的


我假设你有文字,说重复行我的第一行和一些文本我的第二行和更多文本

 我的行一和一些文本
我的行一和一些文本
我的行两个和更多的文本
我的行一个和一些文本
我的行两个和更多的文本

这些重复行并不全部连续(仅前两个)。



因此,您可以通过运行此搜索和替换来删除重复行:

  ^(。+)\r?\\\
(?= [\s\S] *? ^ \1 $)

用空字符串替换



正则表达式注释:默认情况下, ^ $ 被视为行开始/结束锚点,所以我们只匹配一行,并用 ^(。+)$ 捕获它。然后我们将换行符号(任何操作系统风格)与 \r?\\\
匹配。先行(?= ...)检查是否有任何文本( [\s\S] *?是对所捕获的行文本的反向引用。)




I use the following expression in Notepad++ to delete duplicate lines:

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

The problems are:

  1. It is only for single word lines, if there is space in a line it won't work.
  2. It is only for consecutive duplicate lines.

Is there a solution (preferably regular expression or macro) to delete duplicate lines in a text that contains space, and that are nonconsecutive?

解决方案

Since no one is interested, I will post what I think you need.

delete duplicate lines in a text that contains space, and that are nonconsecutive

I assume you have text having, say duplicate lines My Line One and some text and My Line Two and more text:

My Line One and some text
My Line One and some text
My Line Two and more text
My Line One and some text
My Line Two and more text

These duplicate lines are not all consecutive (only the first two).

So, you can remove duplicate lines by running this search and replace:

^(.+)\r?\n(?=[\s\S]*?^\1$)

Replace with empty string.

Regex note: ^ and $ are treated as line start/end anchors by default, so we only match one line and capture it with ^(.+)$. Then we match the newline symbol (any OS style) with \r?\n. The look-ahead (?=...) checks if there is any text (with [\s\S]*?) after our line under inspection with the same contents (with the ^\1$ where \1 is a backreference to the line text captured).

这篇关于如何使用RegEx删除文本中的非连续行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆