删除在字符串中重复两次以上的字符[重复]

问题描述 投票:3回答:1

这个问题在这里已有答案:

我有这个文字:

F <- "hhhappy birthhhhhhdayyy"

我想删除重复字符,我试过这段代码

https://stackoverflow.com/a/11165145/10718214

并且它有效,但如果重复超过2,我需要删除重复字符,如果重复2次则保留它。

所以我期望的输出是

"happy birthday"

任何帮助?

r regex text-mining
1个回答
4
投票

尝试使用sub,模式为(.)\\1{2,}

F <- ("hhhappy birthhhhhhdayyy")
gsub("(.)\\1{2,}", "\\1", F)

[1] "happy birthday"

正则表达式的解释:

(.)          match and capture any single character
\\1{2,}      then match the same character two or more times

我们只用单个匹配字符替换。数量\\1代表sub中的第一个捕获组。

© www.soinside.com 2019 - 2024. All rights reserved.