日期:2014-05-18  浏览次数:20729 次

正则表达式替换数字问题
result = Regex.Replace(result, @"(<a(?=[^<>]*?id=""t1"").*?href="")[^""]*(""[^>]*>)[\s\S]*?(?=</a>)", string.Format("$1{0}$2{1}", textBox12.Text, textBox11.Text), RegexOptions.IgnoreCase);

我用上面的正则表达式想分别替换 <a id="t1" class=link_blue href="http://article.ednchina.com/Commu/20071219071733.htm">Infonetics:WiMAX设备销售额上升势头增强</a> 中的红色部分,可是如果textBox12.Text中的字符是以数字开始的,替换就出现了问题,原文就被替换成为<a id="t1" class=link_blue href="http://article.ednchina.com/Other/20080108052252.htm$22008国际CES更“绿”了</a>  
为什么把后面>改为了$2,请问应该怎么解决呢?

------解决方案--------------------
可以采用一种替代解决方案,把一次替换改成多次替换从而避免数据混淆的问题
楼主可以参考一下
C# code

 string a = "<a   id=\"t1\"   class=link_blue   href=\"http://article.ednchina.com/Commu/20071219071733.htm\"> Infonetics:WiMAX设备销售额上升势头增强 </a> ";
            string reValue = "1212";
            string reValue1 = "CSDN";

            string regex1 = "(?<=<a[\\s\\S]*?href=\")[^\"']*?(?=\"[^>]*?>)";
            string regex2 = "(?<=<a[^>]+?>)[^<]*?(?=\\</a>)";
            string result = Regex.Replace(a, regex1,reValue);
            result = Regex.Replace(result, regex2, reValue1);

            MessageBox.Show(result);

------解决方案--------------------
给要捕获的组命名就是了:

C# code

result = Regex.Replace(result, @"(?<text1><a(?=[^<>]*?id=""t1"").*?href="")[^""]*(?<text2>""[^>]*>)[\s\S]*?(?=</a>)", string.Format("${text1}{0}${text2}{1}", textBox12.Text, textBox11.Text), RegexOptions.IgnoreCase);