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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With