Generate random strings based on regular expressions in R I'm trying to generate random textual data based on regular expressions. I'd like to be able to do this in R, as I know that R does have regex capabilities. Any leads?
This question has come up before in forums (StackOverflow Post 1, StackOverflow Post 2, etc.), but they always mention solutions based on other programming platforms (perl, .NET, ...), not R.
 A: While generating random data from regular expressions would be a convenient interface, it is not directly supported in R. You could try one level of indirection though: generate random numbers and convert them into strings. For example, to convert a number into a character, you could use the following:
> rawToChar(as.raw(65))
[1] "A"

By carefully selecting the range of the random number to draw you can restrict your self to a desired set of ASCII characters that might correspond to a regular expression, e.g., to the character class [a-zA-Z].
Clearly, this is neither an elegant nor efficient solution, but it is at least native and could give you the desired effect with some boilerplate.
A: Still not a perfect answer, however, Mark Heckmann has suggested using a random string generator which partially solves this problem:
GenRandomString <- function(n=1, lenght=12)
{
  randomString <- c(1:n)                  # initialize vector
  for (i in 1:n)
  {
    randomString[i] <- paste(sample(c(0:9, letters, LETTERS),
                                    lenght, replace=TRUE),
                             collapse="")
  }
  return(randomString)
}
GenRandomString(5,8)

Output: five random strings, 8 characters long
[1] "l42DjAtc" "jW6TdRZw" "5aAvMuDL" "iC3xOvst" "gqgSzE83"

This can be used for various cases, e.g generate keys, names, simulations, etc.
