简体   繁体   English

如何用不同的字符替换字符串中的每个数字?

[英]How to replace each digit in a string with a different character?

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.我正在尝试获取一个字符串,例如“e1e2e3”,以将每个数字替换为不同的字符,在这种情况下将是一个随机数。 Whereas instead of e1e2e3, it could be something like e5e9e1 because each number is replaced with a random one.而不是 e1e2e3,它可能类似于 e5e9e1,因为每个数字都被随机替换。

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. “e1e2e3”将类似于“e2e2e2”,其中每个数字都相同。

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.你快到了,你可以使用 Regex.Replace 的回调为每个替换创建一个随机值,而不是使用单个随机值。

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如果您只想匹配数字 0-9,则可以使用[0-9]而不是\\d因为后者可以匹配所有 Unicode 数字

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查看C# 演示

approach without RegEx没有正则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) Next(int,int)的第二个int参数的旁注

The exclusive upper bound of the random number returned.返回的随机数的唯一上限。 maxValue must be greater than or equal to minValue. maxValue 必须大于或等于 minValue。

if you want values between 0 and 9 , you should use Next(0, 10)如果你想要09之间的值,你应该使用Next(0, 10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM