随机化正则表达式字符串替换
本文关键字:替换 字符串 正则表达式 随机化 | 更新日期: 2023-09-27 18:15:31
我在这里尝试做两件事,首先,为字符串提供伪本地化(让我们说)转换,其次,根据百分比比率随机替换字符串中包含的字符的机会,即:每5%-30%的时间…
此外,除此之外,我需要在字符串的开始,中间或结束(随机化)添加固定数字或特殊字符。
只是为了让大家知道,这是一个随机密码生成器。
我的问题是,我该如何将上述功能纳入我目前正在使用的代码库?更好的是,我怎样才能有效地做到这一点?
谢谢你能提供的任何帮助。
namespace pseudoLocalizer
{
class RegexTuple
{
Regex thisRegex;
string replaceWith;
public RegexTuple(string expression, string replacement)
{
thisRegex = new Regex(expression);
replaceWith = replacement;
}
public string GetReplaceWith()
{
return replaceWith;
}
public Regex GetRegex()
{
return thisRegex;
}
}
class pLocalizeEngine
{
//leet table.
RegexTuple[] arrRegexTuples = {
new RegexTuple ("a", @"@"),
new RegexTuple ("A", @"4"),
new RegexTuple ("b", @"6"),
new RegexTuple ("B", @"8"),
new RegexTuple ("c", @"<"),
new RegexTuple ("C", @"("),
new RegexTuple ("d", @"d"),
new RegexTuple ("D", @"D"),
new RegexTuple ("e", @"3"),
new RegexTuple ("E", @"3"),
new RegexTuple ("f", @"f"),
new RegexTuple ("F", @"F"),
new RegexTuple ("g", @"6"),
new RegexTuple ("G", @"9"),
new RegexTuple ("h", @"#"),
new RegexTuple ("H", @"#"),
new RegexTuple ("i", @"!"),
new RegexTuple ("I", @"1"),
new RegexTuple ("j", @"j"),
new RegexTuple ("J", @"J"),
new RegexTuple ("k", @"k"),
new RegexTuple ("K", @"K"),
new RegexTuple ("l", @"1"),
new RegexTuple ("L", @"7"),
new RegexTuple ("m", @"m"),
new RegexTuple ("M", @"M"),
new RegexTuple ("n", @"~"),
new RegexTuple ("N", @"N"),
new RegexTuple ("o", @"0"),
new RegexTuple ("O", @"0"),
new RegexTuple ("p", @"p"),
new RegexTuple ("P", @"P"),
new RegexTuple ("q", @"q"),
new RegexTuple ("Q", @"Q"),
new RegexTuple ("r", @"2"),
new RegexTuple ("R", @"2"),
new RegexTuple ("s", @"$"),
new RegexTuple ("S", @"5"),
new RegexTuple ("t", @"+"),
new RegexTuple ("T", @"7"),
new RegexTuple ("u", @"u"),
new RegexTuple ("U", @"U"),
new RegexTuple ("v", @"v"),
new RegexTuple ("V", @"V"),
new RegexTuple ("w", @"w"),
new RegexTuple ("W", @"W"),
new RegexTuple ("x", @"x"),
new RegexTuple ("X", @"X"),
new RegexTuple ("y", @"y"),
new RegexTuple ("Y", @"Y"),
new RegexTuple ("z", @"2"),
new RegexTuple ("Z", @"2"),
};
public pLocalizeEngine()
{
//
}
public string Localize(string oldString)
{
string pLocalString = oldString;
foreach (RegexTuple tuple in arrRegexTuples)
{
pLocalString = tuple.GetRegex().Replace(pLocalString, tuple.GetReplaceWith());
}
return pLocalString;
}
}
假设您需要密码生成器,以下是我的建议:
private const string ValidCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890@<()!?~+";
private Random random = new Random();
private string RandomPasswordGenerator(int length)
{
string password = string.Empty;
while (length > 0)
{
password += ValidCharacters[random.Next(0, ValidCharacters.Length - 1)];
length--;
}
return password;
}