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

后端 未结 3 788
孤街浪徒
孤街浪徒 2021-02-05 14:12

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 examp

相关标签:
3条回答
  • 2021-02-05 14:29

    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

    0 讨论(0)
  • 2021-02-05 14:31

    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'
    
    0 讨论(0)
  • 2021-02-05 14:43

    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

    0 讨论(0)
提交回复
热议问题