2

I am trying to get a string, for example, "e1e2e3" to have each digit replaced with a different character, which in this case would be a random number. Whereas instead of e1e2e3, it could be something like e5e9e1 because each number is replaced with a random one.

I tried

string txt = textBox1.Text;
Regex digits = new Regex(@"\d", RegexOptions.None);
Random rand = new Random();
txt = digits.Replace(txt, rand.Next(0, 9).ToString());
MessageBox.Show(txt);

The problem is, every single number is replaced with the same random number. "e1e2e3" would then be something like "e2e2e2" where each number is the same.

2
  • Do you want all 1's to be replaced with the same random digit or do you want them to be different? Commented Jun 24, 2021 at 9:01
  • You would need to use the overload of Replace that takes a MatchEvaluator. Commented Jun 24, 2021 at 9:04

2 Answers 2

3

You are almost there, you can use the callback of Regex.Replace to create a random value for each replacement, instead of using a single random value.

If you just want to match digits 0-9 you can use [0-9] instead of \d as the latter could match all Unicode digits

string txt = textBox1.Text;
Regex digits = new Regex(@"\d", RegexOptions.None);
Random rand = new Random();
txt = digits.Replace(txt, match => rand.Next(0, 9).ToString());
MessageBox.Show(txt);

See a C# demo

Sign up to request clarification or add additional context in comments.

Comments

2

approach without RegEx

string txt = "e1e2e3";           
Random rand = new Random();
string res = string.Concat(txt.Select(x => char.IsDigit(x)?(char)('0'+rand.Next(0, 9)):x));

Side note to the second int parameter of Next(int,int)

The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.

if you want values between 0 and 9, you should use Next(0, 10)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.