Create a random regex string

I already have a random string generation method. But it is slow. I want to improve the method using a regex that doesn't suit me.

My code is:

public string GetRandomString()
{
   var random = new Random();
   string id = new string(Enumerable.Repeat("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 16)
              .Select(s => s[random.Next(s.Length)]).ToArray());
   return id;
}

With regex, I can compress the string: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789for some characters. As well as:

var regex = new Regex(@"[\w\d]{16}");

Is there a way to create a random regex string?

+4
source share
2 answers

You can try the following library to generate a random string from a template: https://github.com/moodmosaic/Fare

var xeger = new Xeger(pattern);
var generatedString = xeger.Generate();

-, , Enumerate.Repeat? ? 16 ? , . , - . :

string dictionaryString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder resultStringBuilder = new StringBuilder();
for (int i=0;i<desiredLength;i++)
{
    resultStringBuilder.Append(dictionaryString[random.Next(dictionary.Length)]);
}
return resultStringBuilder.ToString();
+7

, . Regex - . , .

, , , ( ), .

, . @Access Denied . , , - .

using System;
using System.Text;

namespace RandomString
{
    class Program
    {

        static void Main()
        {
            Console.WriteLine("My new random alphanumeric string is {0}", GetRandomAlphaNumString(12));
            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey(true);
        }

        static char[] charactersAvailable = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
                                             'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                                             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

        public static string GetRandomAlphaNumString(uint stringLength)
        {
            StringBuilder randomString = new StringBuilder();

            Random randomCharacter = new Random();

            for (uint i = 0; i < stringLength; i++)
            {
                int randomCharSelected = randomCharacter.Next(0, (charactersAvailable.Length - 1));

                randomString.Append(charactersAvailable[randomCharSelected]);
            }

            return randomString.ToString();
        }
    }
}
+1

Source: https://habr.com/ru/post/1617556/


All Articles