Regex组字符串替换c#
本文关键字:替换 字符串 Regex | 更新日期: 2023-09-27 18:21:10
目标字符串是"qwer on chat: qwer chat"
。我想将qwer .. etc
替换为已经具有的编码文本(md5)//。但我不想把"on chat:"
替换为文本编码,而"聊天"这个词是要编码的。预期结果为"{md5}{md5}{md5}{md5} on chat: {md5}{md5}{md5}{md5} {md5}{md5}{md5}{md5}"
。我如何在C#中做到这一点?谢谢
public static string GetUniqueKey(int maxSize)
{
char[] chars = new char[62];
chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
byte[] data = new byte[1];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(data);
data = new byte[maxSize];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(maxSize);
foreach (byte b in data)
{
result.Append(chars[b % (chars.Length)]);
}
string l = result.ToString();
return "{"+l+"}";
}
static IDictionary<string, string> map = new Dictionary<string, string>()
{
{"q",GetUniqueKey(5)},
{"w",GetUniqueKey(5)},
{"e",GetUniqueKey(5)},
{"r",GetUniqueKey(5)},
{"a",GetUniqueKey(5)},
{"c",GetUniqueKey(5)},
{"h",GetUniqueKey(5)},
{"t",GetUniqueKey(5)},
{"o",GetUniqueKey(5)},
{"n",GetUniqueKey(5)},
};
public void ccc(string str)
{
var regex = new Regex(String.Join("|", map.Keys.Select(k => Regex.Escape(k))));
string newStr = regex.Replace(str ,m => map[m.Value]);
richTextBox1.AppendText(Environment.NewLine + newStr);
}
不需要正则表达式,只需使用String.Split
和String.Join
:
string s = "qwer on chat: qwer chat";
var parts = s.Split(new string[] {"on chat:"}, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.length; i++) {
// MD5 encode each part here replacing the value in the array
}
var final = string.Join("on chat:", parts);
如果您绝对必须使用正则表达式,您可以执行以下操作:
var r = new Regex(@"^(.*)(on chat:)(.*)$");
var n = r.Replace(s, m=> md5(m.Groups[1].Value) + m.Groups[2].Value + md5(m.Groups[3].Value));
其中CCD_ 7是采用字符串并返回md5编码的字符串的函数。