Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random string with regex

Tags:

c#

regex

I've an already method to generate a random string. But it's slow. I wanna improve the method using regular expression which I'm not good at.

My code:

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;
}

By using regex, I can compress the string: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 to some characters easily. Just like:

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

Is there a way to create a random string with the regex?

like image 284
Tân Avatar asked Nov 26 '15 05:11

Tân


1 Answers

You can try the following library for generating random string from pattern: https://github.com/moodmosaic/Fare

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

Secondly, why do you generate string using Enumerate.Repeat? Why don't you save it in string or cache it? What is the point to repeat it 16 times? I think you generate this string each method call and that's why it's slow. To my mind string interning doesn't work in your code because of code generated string. How about doing it this way:

string dictionaryString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder resultStringBuilder = new StringBuilder();
for (int i=0;i<desiredLength;i++)
{
    resultStringBuilder.Append(dictionaryString[random.Next(dictionary.Length)]);
}
return resultStringBuilder.ToString();
like image 193
Access Denied Avatar answered Oct 17 '22 21:10

Access Denied