日期:2014-05-17  浏览次数:20790 次

【求助】:如何使用正则式对文本进行查找替换?
例句:“中华人民共和国成立于1949年10月1日,I、U、R、#”
查找其中的“1949、10、1、I、U、R、#”
然后替换成“中华人民共和国成立于一九四九年十月一日,电流、电压、电阻、号”

如何用一句正则式进行查找替换呢?
正则

------解决方案--------------------

            System.IO.StreamReader reader1 = new System.IO.StreamReader("e:\\1.txt",Encoding.Default);
            string str = @"中华人民共和国成立于1949年10月1日,I、U、R、#";
            string strmatch = @"(?is)[\d]+
------解决方案--------------------
[a-z]
------解决方案--------------------
#";
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(strmatch);
            System.Text.RegularExpressions.MatchCollection mc = reg.Matches(str);
            foreach (System.Text.RegularExpressions.Match mm in mc)
            {
                MessageBox.Show(mm.Value);
            }

------解决方案--------------------
List<string> wordtomatch = new List<string>() { "1949", "10", "1", "I", "U", "R", "#" };
List<string> replacewith = new List<string>() { "一九四九", "十", "一", "电流", "电压", "电阻", "号" };
wordtomatch.ForEach(x => s = s.Replace(x, replacewith[wordtomatch.FindIndex(y => y == x)]));