Here is a quick little snippet of code which uses allows one to create a sequence of numbers and letters, or any character needed, in a sequence defined by the user. Here is the code

Random rn = new Random();
string charsToUse = "AzByCxDwEvFuGtHsIrJqKpLoMnNmOlPkQjRiShTgUfVeWdXcYbZa1234567890";

MatchEvaluator RandomChar = delegate (Match m)
{
    return charsToUse[rn.Next( charsToUse.Length )].ToString();
};

Console.WriteLine( Regex.Replace( "XXXX-XXXX-XXXX-XXXX-XXXX", "X", RandomChar ) );
// Lv2U-jHsa-TUep-NqKa-jlBx
Console.WriteLine( Regex.Replace( "XXXX", "X", RandomChar ) );
 // 8cPD

What is happening is that in the Regex.Replace we specify a pattern by X’s. Anything which is not an X is ignored and left in the result. We specify what characters to use in the string charsToUse and in this case we have A-Za-z0-9 expressed as written out. When we run the Regex.Replace it returns the pattern we specified with the characters we needed.

Share

Tags: