r - 删除字符串中重复两次以上的字符
问题描述
我有这段文字:
F <- "hhhappy birthhhhhhdayyy"
我想删除重复字符,我试过这段代码
https://stackoverflow.com/a/11165145/10718214
它有效,但如果重复超过 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
。
推荐阅读
- ruby - 成功点击后更改页面:stale element reference: element is not attach to the page document
- bash - 为什么我不能在本地运行一个简单的程序?
- python - 如何在类内的函数内使用另一个文件中的方法
- r - 在 R 中,我如何可视化两列中的频率计数与跨时间的另一基线列的比较?
- rust - 你怎么能在你没有定义的东西上使用序列化和反序列化宏?
- bash - 检查多字命令输出是否以bash中的某个字符串开头
- java - BlobInput 的 Azure 函数绑定问题,没有任何错误
- android - 使用 FIrebase Cloud Functions for Android App 生成 Razorpay OrderId
- pine-script - How to avoid having a stop loss triggered and simultaneous entry of the counter position on bar completion in a Pine script v4 strategy?
- javascript - How to divide a string into an object by '.'?