This is kind of improvement of my previous question: c# generate random string based on pattern
I have code as below:
class Generator
{
private static readonly Random R = new Random();
private static readonly char[] L = { 'a', 'b', 'c', 'd', 'e' };
private static readonly char[] U = { 'A', 'B', 'C', 'D', 'E' };
private static readonly char[] S = { '!', '@', '#', '$', '%' };
public static string FromPattern(string pattern)
{
return Regex.Replace(pattern, @"\[([Ccds])(?::([\d]+))?\]", ReplaceSingleMatch);
}
private static string ReplaceSingleMatch(Match m)
{
int length;
if (!int.TryParse(m.Groups[2].Value, out length))
length = 1;
var output = new StringBuilder();
while (output.Length != length)
{
switch (m.Groups[1].Value)
{
case "d"://digits
output.Append(R.Next(0, 9));
break;
case "c"://lowercase char
output.Append(L[R.Next(L.Length)]);
break;
case "C"://uppercase char
output.Append(U[R.Next(U.Length)]);
break;
case "s"://special char
output.Append(S[R.Next(S.Length)]);
break;
}
}
return output.ToString();
}
}
Using above I can write:
Generator.FromPattern("ID: [d:3][c:2]#[C][s:2]")
And I will get sample output like : ID: 263ac#D$!
So when I enter [d]
I get single digit, if I enter [d:5]
I get 5 digits.
What I would like to add is range, so when I enter [d:2-5]
I would get randomly from 2 to 5 random digits.
My biggest problem is regex, rest is easy :)
I need my regex to search below groups:
[d]
,[d:3]
(it must be number after colon),[d:2-5]
(two numbers separated by dash)
Any suggestion about improvements are welcome!