如何获取字符串并将"."
,","
," "
(即点,逗号或空格)的每个实例替换为从c('|', ':', '@', '*')
中选择的一个随机字符?
说我有这样的字符串
Aenean ut odio dignissim augue rutrum faucibus. Fusce posuere, tellus eget viverra mattis, erat tellus porta mi, at facilisis sem nibh non urna. Phasellus quis turpis quis mauris suscipit vulputate. Sed interdum lacus non velit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;
要获得一个随机字符,我们可以将字符视为向量,然后使用sample
函数选择一个。我首先假设我需要搜索点,逗号或空格,然后使用gsub
函数来替换所有这些?
答案 0 :(得分:3)
鉴于你的澄清,试试这个:
x <- c("this, is nice.", "nice, this is.")
gr <- gregexpr("[., ]", x)
regmatches(x,gr) <- lapply(lengths(gr), sample, x=c('|',':','@','*'))
x
#[1] "this|*is@nice:" "nice@|this*is:"
答案 1 :(得分:2)
以下是chartr
pat <- paste(sample(c('|', ';', '@', '*'), 3), collapse="")
chartr('., ', pat, x)
#[1] "this|*is*nice;" "nice|*this*is;"
x <- c("this, is nice.", "nice, this is.")