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?
Regex examples. A simple example for a regular expression is a (literal) string. For example, the Hello World regex matches the "Hello World" string. .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With