I'm trying to do a simple string generation based on pattern.
My idea was to use Regex to do simple replace.
I've started with simple method:
private static string parseTemplate(string template)
{
return Regex.Replace(template, @"(\[d)((:)?([\d]+)?)\]", RandomDigit());
}
private static string RandomDigit()
{
Random r = new Random();
return r.Next(0, 9).ToString();
}
What this does for now is replacing groups like [d]
, [d:3]
with what supposed to be random digit.
Unfortunately every group is replaced with the same digit, for example if I put test [d][d][d:3]
my method will return test 222
.
I would like to get different digit in every place, like test 361
.
Second problem I have is way to handle length:
right now I must specify [d]
for every digit I want, but it would be easier to specify [d:3]
and get the same output.
I know that there is a project called Fare, but I would like to do this without this library
For now I only search for [d]
, but is this method will work fine there won't be a problem to add other groups for example: [s]
for special characters or any other type of patters.
Edit1
As it was suggested I changed Random to a static variable like so:
private static string parseTemplate(string template)
{
return Regex.Replace(template, @"(\[d)((:)?([\d]+)?)\]", RandomDigit());
}
private static Random r = new Random();
private static string RandomDigit()
{
return r.Next(0, 9).ToString();
}
Problem is that when I call my code like so:
Console.WriteLine(parseTemplate("test [d:2][d:][d]"));
Console.WriteLine(parseTemplate("test [d:2][d:][d]"));
I get output like this
test 222
test 555
I would like output like this (for example):
test 265
test 962
I think that problem is with Regex.Replace
which calls my RandomDigit
only once.