【问题标题】:Replace number with a random number of same amount of digits用相同位数的随机数替换数字
【发布时间】:2018-12-08 17:48:29
【问题描述】:

我有一个包含一些数字的字符串,并用一个随机数替换每个数字。
例如。 “111”应替换为 0-9 之间的 3 个随机数,它们像“364”一样连接起来。

我的想法是匹配一个数字,获取位数,计算尽可能多的随机数并将它们连接起来最终替换我匹配的数字:

test <- "this is 1 example 123. I like the no.37"
gsub("([0-9])", paste0(sample(0:9, nchar("\\1")), collapse = ""), test)

我的目标是创建一个字符串,其中每个数字都替换为随机数字。例如

"this is 3 an example 628. I like the no.09"

我尝试了一些方法,但找不到好的解决方案。

【问题讨论】:

    标签: r regex gsub


    【解决方案1】:

    使用gsubfn 库,它会让事情变得更简单:

    library(gsubfn)
    test <- "this is 1 example 123. I like the no.37"
    gsubfn("[0-9]+", ~ paste0(sample(0:9, nchar(x)), collapse = ""), test)
    [1] "this is 8 example 205. I like the no.37"
    

    在这里,gsubfn 将匹配字符串中的所有 1 个或多个数字(请参阅 [0-9]+ 模式)。然后,匹配项被传递给回调,nchar 获取捕获的子字符串(数字子字符串)的实际值。

    【讨论】:

      猜你喜欢
      • 2020-08-14
      • 2012-06-24
      • 1970-01-01
      • 2017-04-17
      • 2017-03-06
      • 2020-12-26
      • 2017-05-20
      • 2013-11-04
      • 2022-07-25
      相关资源
      最近更新 更多