首页 > 解决方案 > 删除字符串中重复两次以上的字符

问题描述

我有这段文字:

F <- "hhhappy birthhhhhhdayyy"

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

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

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

所以我期望的输出是

"happy birthday"

有什么帮助吗?

标签: rregextext-mining

解决方案


尝试使用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


推荐阅读