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

求C#正则查找替换一段字符串
XML code

<Run Tag="/qqqq/qqqqq" xml:space="preserve"> </Run>
<Run Tag="end" xml:space="preserve"> </Run>
<Run Tag="/aaa/aaa" xml:space="preserve"> </Run>
<Run Tag="end" xml:space="preserve"> </Run>


替换成下面这样
XML code

<Canvas Tag="/qqqq/qqqqq" Width="0"/>
<Canvas Tag="end" Width="0"/>
<Canvas Tag="/aaa/aaa" Width="0"/>
<Canvas Tag="end" Width="0"/>


条件是 Tag!="" 的Run才替换 
替换后Tag不变  

求高手...........

------解决方案--------------------
没注意到还有一个结尾标签!
C# code

            string str=@"<Run Tag=""/qqqq/qqqqq"" xml:space=""preserve""> </Run>
<Run Tag=""end"" xml:space=""preserve""> </Run>
<Run Tag=""/aaa/aaa"" xml:space=""preserve""> </Run>
<Run Tag=""end"" xml:space=""preserve""> </Run>
<Run Tag="""" xml:space=""preserve""> </Run>";
            string result = Regex.Replace(str, @"(?i)<Run\s+(Tag=""[^""]+"")[^>]*?>\s*</Run>", "<Canvas $1 Width=\"0\"/>");
            Console.WriteLine(result);
/*
<Canvas Tag="/qqqq/qqqqq" Width="0"/>
<Canvas Tag="end" Width="0"/>
<Canvas Tag="/aaa/aaa" Width="0"/>
<Canvas Tag="end" Width="0"/>
<Run Tag="" xml:space="preserve"> </Run>

*/