问题描述
有什么问题:
1: This is test string for my app. d
2: This is test string for my app.
3: This is test string for my app. abcd
4: This is test string for my app.
5: This is test string for my app.
6: This is test string for my app.
7: This is test string for my app. d
8: This is test string for my app.
9: This is test string for my app.
10: This is another string.
这里的行号只是为了更好的可视化,它们不是文本本身的一部分。
我尝试过的:
我尝试了两种不同的正则表达式(标志总是:i
g
和 m
):
^([^\r\n]*)$(.*?)(?:(?:\r?\n|\r)\1)+$
请看这里:regexr.com/5nklg
和
^(.*)(?:\r?\n|\r)(?=[\s\S]*^\1$)
请看这里:regexr.com/5nkla
它们都产生不同的输出,都很好,但并不完美。
我想要达到的目标:
删除文本中所有重复的短语,但保留一个。例如,这里保留第一个“这是我的应用程序的测试字符串”。从第 1 行开始,匹配第 2-9 行的相同短语并保留数字 10。
如果我可以保留最后一个而不是第一个匹配短语,它也对我有用。所以这里这将是匹配行 1 - 8,保留 9 和 10。
有没有办法用正则表达式做到这一点?
仅供参考:稍后我将在 python 中使用正则表达式来删除重复项:
re.sub(r"^(.*)(?:\r?\n|\r)(?=[\s\S]*^\1$)","",my_text,flags=re.MULTILINE)
编辑:“短语”意味着让我们说 3 个或更多单词。所以匹配任何超过 2 个单词的重复。所以第一个 sub 之后的预期输出是:
This is test string for my app. d //from line 1
This is test string for my app. //from line 2
abcd //from line 3
This is another string. //from line 10
提前致谢!
解决方法
你可以使用
re.sub(r'^(([^\n\r.]*).*)(?:(?:\r?\n|\r)\2.*)*',r'\1',my_text,flags=re.M)
参见regex demo。
详情:
-
^
- 行首(由于使用了re.M
选项,^
现在匹配行首位置) -
(([^\n\r.]*).*)
- 第 1 组:除点、CR 和 LF 之外的零个或多个字符被捕获到第 2 组中,然后是该行的其余部分 -
(?:(?:\r?\n|\r)\2.*)*
- 零个或多个序列-
(?:\r?\n|\r)
- CRLF、CR 或 LF 行结束 -
\2
- 与第 2 组中的文本相同 -
.*
- 该行的其余部分。
-
替换为第 1 组值。