用相同位数的随机数替换数字
Replace number with a random number of same amount of digits
我有一个包含一些数字的字符串,并用一个随机数替换每个数字。
例如。 “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"
我尝试了一些方法,但找不到好的解决方案。
使用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
获取捕获的子字符串(数字子字符串)的实际值。
我有一个包含一些数字的字符串,并用一个随机数替换每个数字。
例如。 “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"
我尝试了一些方法,但找不到好的解决方案。
使用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
获取捕获的子字符串(数字子字符串)的实际值。