Regular Expressions (aka Regex) are popular because it lets validate your data. Developers use them to validate input controls for emails, phone numbers, or usernames.
In .NET we have the Regex
class which can validate a string based on a pattern. What if you want to generate a string from a pattern, instead of validating it. Then you can use Fare library
Fare library is a port of the Java library dk.brics.automaton. It uses finite state machines like DFA and NFA.
How to generate strings from Regex
- Install the NuGet package for the Fare library
Install-Package Fare
- Create a new instance of Xeger class and start generating patterns:
using Fare; ... Xeger xeger = new Xeger(@"^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$"); // Regex for US number for (int i = 0; i < 100; i++) { Console.WriteLine(xeger.Generate()); }
Fare library use cases
If you don’t know where you can use it, here are some scenarios:
- generate input data for Unit tests
- generate valid random data starting from the validation rules
I have once used the Fare library and the libphonenumber library to generate phone numbers that are valid.