14

In my application the user can enter his own regex pattern into a text box so he can force a certain input for another user/text box. Is it possible for the user to see an example of a string that would match the regex he has entered? For example if he was to enter: ^[A-Z]{2}$, it would generate a string like "XX" to show the user he can only enter two capital letters.

If there's no easy way to accomplish this (and I assume there isn't), how difficult would it be to build? Or does something like this already exist?

Pontus Gagge
  • 17,166
  • 1
  • 38
  • 51
Fusyion
  • 704
  • 1
  • 12
  • 23
  • see http://stackoverflow.com/questions/205411/random-string-that-matches-a-regexp, it may help you. – Shimrod Jun 28 '10 at 09:25

3 Answers3

8

Check out Xeger. It looks like it can do what you want. It's in Java though.

Here is an example from the test suite:

   @Test
    public void shouldGenerateTextCorrectly() {
        String regex = "[ab]{4,6}c";
        Xeger generator = new Xeger(regex);
        for (int i = 0; i < 100; i++) {
            String text = generator.generate();
            assertTrue(text.matches(regex));
        }
    }

Update: thanks to Nikos Baxevanis, the dk.brics.automaton have been ported to C# at https://github.com/moodmosaic/Fare

Veverke
  • 9,208
  • 4
  • 51
  • 95
Martin Wickman
  • 19,662
  • 12
  • 82
  • 106
  • That's exactly what I'm looking for.. but for C#. At least I have something I can use as reference. – Fusyion Jun 28 '10 at 09:39
  • Xeger is just a thin wrapper around http://www.brics.dk/~amoeller/automaton/ which is DFA/NFA implementation of some regexp operations. Maybe there is something like that available for C# somewhere? – Martin Wickman Jun 28 '10 at 09:52
  • 1
    @MartinWickman Yes, both the dk.brics.automaton and the xeger sources have been ported to C# at https://github.com/moodmosaic/Fare – Nikos Baxevanis Nov 08 '12 at 18:14
8

For C# you may also want to look at project Fare. For more details have a look at this answer.

Example

var regex = @"((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)";
var xeger = new Xeger(regex);

var result = Regex.IsMatch(xeger.Generate(), regex);
// -> Prints 'true'
Community
  • 1
  • 1
Nikos Baxevanis
  • 10,868
  • 2
  • 46
  • 80
0

I once needed such thing too, so I created a simple program with gui using xeger lib mentioned above. Simply run .jar from dist folder (jre is required) https://github.com/ogyct/SampleFromRegex

Dmitry Avgustis
  • 854
  • 1
  • 9
  • 14