删除字符串中重复两次以上的字符
Remove characters which repeat more than twice in a string
我有这段文字:
F <- "hhhappy birthhhhhhdayyy"
我想删除重复字符,我试过这段代码
它有效,但如果重复超过 2 个,我需要删除重复字符,如果重复 2 次,则保留它。
所以我期望的输出是
"happy birthday"
有什么帮助吗?
尝试使用 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
中的第一个捕获组。
我有这段文字:
F <- "hhhappy birthhhhhhdayyy"
我想删除重复字符,我试过这段代码
它有效,但如果重复超过 2 个,我需要删除重复字符,如果重复 2 次,则保留它。
所以我期望的输出是
"happy birthday"
有什么帮助吗?
尝试使用 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
中的第一个捕获组。