r - 替换文本中大于 5 位的数字
问题描述
a <- c("this is a number 9999333333 and i got 12344")
我怎么能用额外的数字替换大于5位的数字是“X”
预期输出:
"this is a number 99993XXXXX and i got 12344"
我试过的代码:
gsub("(.{5}).*", "X", a)
解决方案
您可以使用gsub
PCRE 正则表达式:
(?:\G(?!^)|(?<!\d)\d{5})\K\d
请参阅正则表达式演示。细节:
(?:\G(?!^)|(?<!\d)\d{5})
- 上一个成功匹配的结尾 (\G(?!^)
) 或 (|
) 前面没有数字 ((?<!\d)
) 和任何五个数字的位置\K
- 匹配重置运算符丢弃到目前为止匹配的所有文本\d
- 一个数字。
请参阅R 演示:
a <- c("this is a number 9999333333 and i got 12344")
gsub("(?:\\G(?!^)|(?<!\\d)\\d{5})\\K\\d", "X", a, perl=TRUE)
## => [1] "this is a number 99993XXXXX and i got 12344"
推荐阅读
- python - 我对我的 Python 感到困惑。ValueError:对已关闭文件的 I/O 操作
- excel - 使用 PowerShell 在 Excel 中批量添加超链接
- node.js - Nginx 反向代理仅 xhr/ajax 请求
- python - 在 Python 3 中对列进行分组和提取统计信息
- mysql - MYSQL - 自连接与连接表
- django - 在 Django REST 中更新作者的实例
- c++ - 在一个联合内的不同匿名联合中具有相同名称的字段
- git - Git强制删除VSCode中的小写-d
- java - 表列未填充,是控制器还是连接表问题?
- c#-4.0 - Task.Run 是否保证每个方法都将运行完成