首页 > 解决方案 > 替换文本中大于 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)

标签: rregexgsubregex-groupdata-masking

解决方案


您可以使用gsubPCRE 正则表达式:

(?:\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"

推荐阅读