Skip to content

Getting Started

janzsch edited this page Nov 14, 2018 · 7 revisions

RegSeed creates random strings from a regex pattern in two steps. In the first step it parses the pattern into a stream of tokens classifying the input elements - this is done by the lexer class. In the second one, the token stream is interpreted according to the supported Backus-Naur-Form. Ultimately, this generates for each subexpression a list of possible characters from which a single character is chosen randomly each time the RegSeed method Generate is called. Note that all characters must be elements from an alphabet specified before hand - if RegSeed is used in its default form a predefined standard alphabet is used.

There are essentially two ways to use RegSeed depending on whether you know if your provided regex pattern is valid/supported or not.
In the first case, just pass the regex pattern to the RegSeed constructor - you should however be aware that in case the regex pattern is malformed an exception is thrown.

public void Main(string[] argv)
{
    const string pattern = "[Hh]allo (W|w)orld!";
    var regseed = new RegSeed(pattern);  // does not throw, since pattern is valid
    
    Console.WriteLine(regseed.Generate());
    Console.WriteLine(regseed.Generate());

    const string malformedPattern = "[Hhallo (W|w)orld!";
    var regseed = new RegSeed(pattern);  // throws exception as the character class bracket '[' is never closed
}

If you are not sure, your regex pattern is valid you can create a RegSeed instance without passing the pattern to the constructor. Instead, you can call the method TryLoadRegexPattern which returns an IParseResult containing information whether the loading of the regex succeeded and, if not, at which position and why the regex string was malformed. Afterwards, you can continue in generating random strings as above provided the loading of the pattern succeeded.

public void Main(string[] argv)
{
    const string malformedPattern = "([Hh]allo (W|w)orld!){X,2}";
    var regseed = new RegSeed();
    
    IParseResult parseResult = regseed.TryLoadRegexPattern(malformedPattern);

    if (!parseResult.IsSuccess) 
    {
        Console.WriteLine($"The provided regex pattern '{malformedPattern}' is malformed at position {parseresult.Position}. ErrorCode: {parseResult.ErrorCode}");
        return;
    }
    
    Console.WriteLine(regseed.Generate());
}

For a more detailed description of RegSeed's capabilities see API.


Previous
Next