# 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.

-
I like the Xeger solution linked to in the first post: it obtains the deterministic FSA created by the system and then makes random transitions within it. (The snarky negative comments in the second post seem altogether ignorant of that simple, valid approach). AFAIK, nothing in R provides the equivalent capability. Consider using something like Xeger to generate a text file of strings and then read it into R for the intended statistical processing. –  whuber Mar 4 '11 at 22:59
Or make a "RXeger" wrapper package with rJava and than post it on CRAN ;-) –  mbq Mar 4 '11 at 23:45

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.

-
Thanks, @Matthias Vallentin. I've just used this for generation of a random length word based on a simple regular expression. I had been unable to do the same in Excel earlier. However, it would be nice to have a more robust approach in the future! –  drapkin11 Mar 5 '11 at 1:28
(+1) For the function rawToChar which I did not know. –  gui11aume Jun 17 '12 at 16:05