正则表达式组字符串替换c#

时间:2014-09-09 17:22:21

标签: c# regex

目标字符串为"qwer on chat: qwer chat"。我想将qwer .. etc替换为已有的编码文本(md5)//。但是,我不想将"on chat:"替换为文字编码,而“#34;聊天”这个词则是#34}。是要编码。预期结果为"{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);
    }

1 个答案:

答案 0 :(得分:0)

不需要正则表达式,您可以使用String.SplitString.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));

其中md5是一个接受字符串并返回md5编码字符串的函数。