r - stringr:我想删除两侧有空格的杂散字符(最多两个)
问题描述
我很难用 stringr 实现以下目标:我想删除两侧有空格的杂散字符(最多两个)。我无法让 stringr 在没有错误的情况下给我很好的结果。下面是两个例子。先感谢您。
string1<-'john a smith'
output1<-'john smith'
string2<-'betty ao smith'
output2<-'betty smith'
解决方案
gsub(" \\S{1,2} ", " ", c('john a smith', 'betty ao smith'))
# [1] "john smith" "betty smith"
\\S
是非空格字符{.}
允许重复前面的模式;例如{2,}
至少 2{,3}
不超过 3{1,2}
1到2之间
同样stringr
,因为它是“只是正则表达式”:-)
stringr::str_replace(c('john a smith', 'betty ao smith'), " \\S{1,2} ", " ")
推荐阅读
- python - 防止自动完成框出现
- github-pages - github-pages 200.html 支持
- javascript - Azure Functions HTTP 端点参数有空格
- java - 使用枚举版本单例模式时,修改单例类代码是扩展单例功能的唯一方法吗?
- sql - 如何在没有子查询的情况下依靠 DISTINCT ON
- android - Androidx Constraintlayout 对 Android Studio 无响应
- loops - Ansible 循环中的反向引用
- python - boto3 aws 检查 s3 存储桶是否已加密
- python - 不知道为什么图长时间不编译执行代码
- sql - 在 SELECT CASE 查询中使用 REPLACE 函数