<p>I am writing a Java utility that helps me to generate loads of data for performance testing. It would be <em>really</em> cool to be able to specify a regex for Strings so that my generator spits out things that match this.</p>
<p>Is something out there already baked that I can use to do this?  Or is there a library that gets me most of the way there?</p>

[{'answer_id': 22132, 'author': 'Espo', 'author_id': 2257, 'author_profile': 'https://Stackoverflow.com/users/2257', 'pm_score': 2, 'selected': False, 'text': '<p>You\'ll have to write your own parser, like the author of String::Random (Perl) did. In fact, he doesn\'t use regexes anywhere in that module, it\'s just what perl-coders are used to.</p>\n<p>On the other hand, maybe you can have a look at <a href="http://search.cpan.org/%7Esteve/String-Random-0.20/Random.pm" rel="nofollow noreferrer">the source</a>, to get some pointers.</p>\n<hr />\n<p>EDIT: Damn, blair beat me to the punch by 15 seconds.</p>\n'}, {'answer_id': 22133, 'author': 'Cheekysoft', 'author_id': 1820, 'author_profile': 'https://Stackoverflow.com/users/1820', 'pm_score': 7, 'selected': True, 'text': '<p><strong>Edit:</strong></p>\n<p>Complete list of suggested libraries on this question:</p>\n<ol>\n<li><a href="https://code.google.com/archive/p/xeger/" rel="noreferrer">Xeger</a>* - Java</li>\n<li><a href="https://github.com/mifmif/Generex" rel="noreferrer">Generex</a>* - Java</li>\n<li><a href="https://github.com/curious-odd-man/RgxGen" rel="noreferrer">Rgxgen</a> - Java</li>\n<li><a href="https://github.com/GoranSiska/rxrdg" rel="noreferrer">rxrdg</a> - C#</li>\n</ol>\n<p>* - Depends on <code>dk.brics.automaton</code></p>\n<p><strong>Edit:</strong>\nAs mentioned in the comments, there is a library available at Google Code to achieve this:\n<a href="https://code.google.com/archive/p/xeger/" rel="noreferrer">https://code.google.com/archive/p/xeger/</a></p>\n<p>See also <a href="https://github.com/mifmif/Generex" rel="noreferrer">https://github.com/mifmif/Generex</a> as suggested by <a href="https://stackoverflow.com/a/24659605/1820">Mifmif</a></p>\n<p><strong>Original message:</strong></p>\n<p>Firstly, with a complex enough regexp, I believe this can be impossible. But you should be able to put something together for simple regexps.</p>\n<p>If you take a look at the source code of the class java.util.regex.Pattern, you\'ll see that it uses an internal representation of Node instances. Each of the different pattern components have their own implementation of a Node subclass. These Nodes are organised into a tree.</p>\n<p>By producing a visitor that traverses this tree, you should be able to call an overloaded generator method or some kind of Builder that cobbles something together.</p>\n'}, {'answer_id': 22163, 'author': 'Craig', 'author_id': 1611, 'author_profile': 'https://Stackoverflow.com/users/1611', 'pm_score': 2, 'selected': False, 'text': '<p>On stackoverflow podcast 11:</p>\n\n<blockquote>\n  <p>Spolsky:  Yep.  There\'s a new product also, if you don\'t want to use the Team System there our friends at Redgate have a product called SQL Data Generator [<a href="http://www.red-gate.com/products/sql_data_generator/index.htm]" rel="nofollow noreferrer">http://www.red-gate.com/products/sql_data_generator/index.htm]</a>.  It\'s $295, and it just generates some realistic test data.  And it does things like actually generate real cities in the city column that actually exist, and then when it generates those it\'ll get the state right, instead of getting the state wrong, or putting states into German cities and stuff like... you know, it generates pretty realistic looking data.  I\'m not really sure what all the features are.</p>\n</blockquote>\n\n<p>This is probably not what you are looking for, but it might be a good starting off point, instead of creating your own.</p>\n\n<p>I can\'t seem to find anything in google, so I would suggest tackling the problem by parsing a given regular expression into the smallest units of work (\\w, [x-x], \\d, etc) and writing some basic methods to support those regular expression phrases.</p>\n\n<p>So for \\w you would have a method getRandomLetter() which returns any random letter, and you would also have getRandomLetter(char startLetter, char endLetter) which gives you a random letter between the two values.</p>\n'}, {'answer_id': 245381, 'author': 'J Wynia', 'author_id': 1124, 'author_profile': 'https://Stackoverflow.com/users/1124', 'pm_score': 2, 'selected': False, 'text': "<p>I know there's already an accepted answer, but I've been using <strong>RedGate's Data Generator</strong> (the one mentioned in Craig's answer) and it works REALLY well for everything I've thrown at it. It's quick and that leaves me wanting to use the same regex to generate the real data for things like registration codes that this thing spits out.</p>\n\n<p>It takes a regex like:</p>\n\n<pre><code>[A-Z0-9]{3,3}-[A-Z0-9]{3,3}\n</code></pre>\n\n<p>and it generates tons of unique codes like:</p>\n\n<pre><code>LLK-32U\n</code></pre>\n\n<p>Is this some big secret algorithm that RedGate figured out and we're all out of luck or is it something that us mere mortals actually could do?</p>\n"}, {'answer_id': 280105, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>It\'s far from supporting a full PCRE regexp, but I wrote the following Ruby method to take a regexp-like string and produce a variation on it. (For language-based CAPTCHA.)</p>\n\n<pre><code># q = "(How (much|many)|What) is (the (value|result) of)? :num1 :op :num2?"\n# values = { :num1=>42, :op=>"plus", :num2=>17 }\n# 4.times{ puts q.variation( values ) }\n# => What is 42 plus 17?\n# => How many is the result of 42 plus 17?\n# => What is the result of 42 plus 17?\n# => How much is the value of 42 plus 17?\nclass String\n  def variation( values={} )\n    out = self.dup\n    while out.gsub!( /\\(([^())?]+)\\)(\\?)?/ ){\n      ( $2 && ( rand > 0.5 ) ) ? \'\' : $1.split( \'|\' ).random\n    }; end\n    out.gsub!( /:(#{values.keys.join(\'|\')})\\b/ ){ values[$1.intern] }\n    out.gsub!( /\\s{2,}/, \' \' )\n    out\n  end\nend\n\nclass Array\n  def random\n    self[ rand( self.length ) ]\n  end\nend</code></pre>\n'}, {'answer_id': 412989, 'author': 'Goran', 'author_id': 23164, 'author_profile': 'https://Stackoverflow.com/users/23164', 'pm_score': 3, 'selected': False, 'text': '<p>I\'ve gone the root of rolling my <a href="https://github.com/GoranSiska/rxrdg" rel="nofollow noreferrer">own</a> library for that (In c# but should be easy to understand for a Java developer).</p>\n\n<p>Rxrdg started as a solution to a problem of creating test data for a real life project. The basic idea is to leverage the existing (regular expression) validation patterns to create random data that conforms to such patterns. This way valid random data is created. </p>\n\n<p>It is not that difficult to write a parser for simple regex patterns. Using an abstract syntax tree to generate strings should be even easier.</p>\n'}, {'answer_id': 1590630, 'author': 'Wilfred Springer', 'author_id': 136476, 'author_profile': 'https://Stackoverflow.com/users/136476', 'pm_score': 4, 'selected': False, 'text': '<p><a href="https://github.com/MukulShukla/xeger" rel="noreferrer">Xeger (Java)</a> is capable of doing it as well:</p>\n\n<pre><code>String regex = "[ab]{4,6}c";\nXeger generator = new Xeger(regex);\nString result = generator.generate();\nassert result.matches(regex);\n</code></pre>\n'}, {'answer_id': 12151715, 'author': 'R dhabalia', 'author_id': 1629062, 'author_profile': 'https://Stackoverflow.com/users/1629062', 'pm_score': 2, 'selected': False, 'text': '<p>I am on flight and just saw the question: I have written easiest but inefficient and incomplete solution. I hope it may help you to start writing your own parser:</p>\n\n<pre><code>public static void main(String[] args) {\n\n    String line = "[A-Z0-9]{16}";\n    String[] tokens = line.split(line);\n    char[] pattern = new char[100];\n    int i = 0;\n    int len = tokens.length;\n    String sep1 = "[{";\n    StringTokenizer st = new StringTokenizer(line, sep1);\n\n    while (st.hasMoreTokens()) {\n        String token = st.nextToken();\n        System.out.println(token);\n\n        if (token.contains("]")) {\n            char[] endStr = null;\n\n            if (!token.endsWith("]")) {\n                String[] subTokens = token.split("]");\n                token = subTokens[0];\n\n                if (!subTokens[1].equalsIgnoreCase("*")) {\n                    endStr = subTokens[1].toCharArray();\n                }\n            }\n\n            if (token.startsWith("^")) {\n                String subStr = token.substring(1, token.length() - 1);\n                char[] subChar = subStr.toCharArray();\n                Set set = new HashSet&lt;Character&gt;();\n\n                for (int p = 0; p &lt; subChar.length; p++) {\n                    set.add(subChar[p]);\n                }\n\n                int asci = 1;\n\n                while (true) {\n                    char newChar = (char) (subChar[0] + (asci++));\n\n                    if (!set.contains(newChar)) {\n                        pattern[i++] = newChar;\n                        break;\n                    }\n                }\n                if (endStr != null) {\n                    for (int r = 0; r &lt; endStr.length; r++) {\n                        pattern[i++] = endStr[r];\n                    }\n                }\n\n            } else {\n                pattern[i++] = token.charAt(0);\n            }\n        } else if (token.contains("}")) {\n            char[] endStr = null;\n\n            if (!token.endsWith("}")) {\n                String[] subTokens = token.split("}");\n                token = subTokens[0];\n\n                if (!subTokens[1].equalsIgnoreCase("*")) {\n                    endStr = subTokens[1].toCharArray();\n                }\n            }\n\n            int length = Integer.parseInt((new StringTokenizer(token, (",}"))).nextToken());\n            char element = pattern[i - 1];\n\n            for (int j = 0; j &lt; length - 1; j++) {\n                pattern[i++] = element;\n            }\n\n            if (endStr != null) {\n                for (int r = 0; r &lt; endStr.length; r++) {\n                    pattern[i++] = endStr[r];\n                }\n            }\n        } else {\n            char[] temp = token.toCharArray();\n\n            for (int q = 0; q &lt; temp.length; q++) {\n                pattern[i++] = temp[q];\n            }\n        }\n    }\n\n    String result = "";\n\n    for (int j = 0; j &lt; i; j++) {\n        result += pattern[j];\n    }\n\n    System.out.print(result);\n}\n</code></pre>\n'}, {'answer_id': 24659605, 'author': 'Mifmif', 'author_id': 1250229, 'author_profile': 'https://Stackoverflow.com/users/1250229', 'pm_score': 5, 'selected': False, 'text': '<p>It\'s too late to help the original poster, but it could help a newcomer. <a href="https://github.com/mifmif/Generex" rel="noreferrer">Generex</a> is a useful java library that provides many features for using regexes to generate strings (random generation, generating a string based on its index, generating all strings...).</p>\n\n<p>Example :</p>\n\n<pre><code>Generex generex = new Generex("[0-3]([a-c]|[e-g]{1,2})");\n\n// generate the second String in lexicographical order that matches the given Regex.\nString secondString = generex.getMatchedString(2);\nSystem.out.println(secondString);// it print \'0b\'\n\n// Generate all String that matches the given Regex.\nList&lt;String&gt; matchedStrs = generex.getAllMatchedStrings();\n\n// Using Generex iterator\nIterator iterator = generex.iterator();\nwhile (iterator.hasNext()) {\n    System.out.print(iterator.next() + " ");\n}\n// it prints 0a 0b 0c 0e 0ee 0e 0e 0f 0fe 0f 0f 0g 0ge 0g 0g 1a 1b 1c 1e\n// 1ee 1e 1e 1f 1fe 1f 1f 1g 1ge 1g 1g 2a 2b 2c 2e 2ee 2e 2e 2f 2fe 2f 2f 2g\n// 2ge 2g 2g 3a 3b 3c 3e 3ee 3e 3e 3f 3fe 3f 3f 3g 3ge 3g 3g 1ee\n\n// Generate random String\nString randomStr = generex.random();\nSystem.out.println(randomStr);// a random value from the previous String list\n</code></pre>\n\n<p><strong>Disclosure</strong></p>\n\n<p>The project mentioned on this post belongs to the user answering (Mifmif) the question. As per the <a href="https://stackoverflow.com/help/behavior">rules</a>, this need to be brought up.</p>\n'}, {'answer_id': 42824600, 'author': 'Angelo Gargantini', 'author_id': 7584324, 'author_profile': 'https://Stackoverflow.com/users/7584324', 'pm_score': 0, 'selected': False, 'text': '<p>If you want to generate "critical" strings, you may want to consider:</p>\n\n<p>EGRET <a href="http://elarson.pythonanywhere.com/" rel="nofollow noreferrer">http://elarson.pythonanywhere.com/</a>\nthat generates "evil" strings covering your regular expressions</p>\n\n<p>MUTREX <a href="http://cs.unibg.it/mutrex/" rel="nofollow noreferrer">http://cs.unibg.it/mutrex/</a>\nthat generates fault-detecting strings by regex mutation</p>\n\n<p>Both are academic tools (I am one of the authors of the latter) and work reasonably well.</p>\n'}, {'answer_id': 45135063, 'author': 'Everett', 'author_id': 274030, 'author_profile': 'https://Stackoverflow.com/users/274030', 'pm_score': 1, 'selected': False, 'text': '<p>This question is very old, but I stumbled across it on my own search, so I will include a couple links for others who might be searching for the same functionality in other languages.</p>\n\n<ul>\n<li>There is a Node.js library here: <a href="https://github.com/fent/randexp.js" rel="nofollow noreferrer">https://github.com/fent/randexp.js</a></li>\n<li>There is a PHP library here: <a href="https://github.com/icomefromthenet/ReverseRegex" rel="nofollow noreferrer">https://github.com/icomefromthenet/ReverseRegex</a></li>\n<li>The PHP faker package includes a "regexify" method that accomplishes this: <a href="https://packagist.org/packages/fzaninotto/faker" rel="nofollow noreferrer">https://packagist.org/packages/fzaninotto/faker</a></li>\n</ul>\n'}, {'answer_id': 58813696, 'author': 'Vladislav Varslavans', 'author_id': 4174003, 'author_profile': 'https://Stackoverflow.com/users/4174003', 'pm_score': 4, 'selected': False, 'text': '<p>This question is really old, though the problem was actual for me.\nI\'ve tried <a href="http://code.google.com/p/xeger" rel="nofollow noreferrer">xeger</a> and <a href="https://github.com/mifmif/Generex" rel="nofollow noreferrer">Generex</a> and they doesn\'t seem to meet my reguirements.\nThey actually fail to process some of the regex patterns (like <code>a{60000}</code>) or for others (e.g. <code>(A|B|C|D|E|F)</code>) they just don\'t produce all possible values. Since I didn\'t find any another appropriate solution - I\'ve created my own library.</p>\n<p><a href="https://github.com/curious-odd-man/RgxGen" rel="nofollow noreferrer">https://github.com/curious-odd-man/RgxGen</a></p>\n<p>This library can be used to generate both matching and non-matching string.</p>\n<p>There is also artifact on maven central available.</p>\n<p>Usage example:</p>\n<pre><code>RgxGen rgxGen = new RgxGen(aRegex);                     // Create generator\nString s = rgxGen.generate();                           // Generate new random value\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/22115', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2455/']