Paul Endymion
Paul Endymion

Reputation: 561

Generate part-random strings from regex

I have a set of complex identifiers that are the column names of a dataframe. This regular expression matches all of them :

regex <- "^PLUTO-.{2}-.{4}-01.{1}-.{3}-.{4}-.{2}$"

Now I would like to generate random identifiers using this regex to get something like this :

"PLUTO-xx-xxxx-01x-xxx-xxxx-xx"
"PLUTO-xx-xxxx-01x-xxx-xxxx-xx"
...

Where x's are random characters.

Is there a function that does such things in R? I found such topics for java and python but nothing in R (only paste() and collapse() solutions).

Upvotes: 1

Views: 148

Answers (1)

akrun
akrun

Reputation: 887223

One option is gsubfn

library(gsubfn)
gsub("\\^|\\$", "", gsubfn("\\.{([[:digit:]]+)}", ~ paste(rep("x", n), collapse=""), regex))
#[1] "PLUTO-xx-xxxx-01x-xxx-xxxx-xx"

Upvotes: 1

Related Questions