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

Fat*_*ima 6 regex r text-mining

我有这样的文字:

F <- "hhhappy birthhhhhhdayyy"
Run Code Online (Sandbox Code Playgroud)

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

/sf/answers/781560181/

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

所以我期望的输出是

"happy birthday"
Run Code Online (Sandbox Code Playgroud)

有什么帮助吗?

Tim*_*sen 6

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

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

[1] "happy birthday"
Run Code Online (Sandbox Code Playgroud)

正则表达式说明:

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

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

  • @Cath 按照 OP 的字面意思,我们只想替换出现在一系列 _three_ 或更多字母中的字母。您的建议将在 _two_ 或更多上进行替换。 (2认同)