Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to generate an example string based on a regex pattern?

Tags:

string

c#

regex

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?

like image 201
Fusyion Avatar asked Jun 28 '10 09:06

Fusyion


People also ask

Can regex be a string?

Regex examples. A simple example for a regular expression is a (literal) string. For example, the Hello World regex matches the "Hello World" string. .

What is a regex give an example of a regex pattern?

A regex (regular expression) consists of a sequence of sub-expressions. In this example, [0-9] and + . The [...] , known as character class (or bracket list), encloses a list of characters. It matches any SINGLE character in the list.

Is regex only used for strings?

So, yes, regular expressions really only apply to strings. If you want a more complicated FSM, then it's possible to write one, but not using your local regex engine.


1 Answers

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

like image 157
Martin Wickman Avatar answered Oct 05 '22 23:10

Martin Wickman