Fat*_*ima 6 regex r text-mining
我有这样的文字:
F <- "hhhappy birthhhhhhdayyy"
Run Code Online (Sandbox Code Playgroud)
我想删除重复字符,我试过这个代码
它有效,但如果重复超过 2 个,我需要删除重复字符,如果重复 2 次,则保留它。
所以我期望的输出是
"happy birthday"
Run Code Online (Sandbox Code Playgroud)
有什么帮助吗?
尝试使用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。