闲坐敲棋

有约不来过夜半,闲敲棋子落灯花

导航

c# 正则数组替换

Posted on 2012-01-10 22:34  闲坐敲棋  阅读(337)  评论(0编辑  收藏  举报

 

用法:配置字符串如 xml

     <AttrList>
      <Attr Name="TemplateId">1</Attr>
      <Attr Name="AppId">$0$</Attr>
      <Attr Name="BookId">$1$</Attr>
      <Attr Name="IsVip">$3$</Attr>
      <Attr Name="Status">$4$</Attr>
      <Attr Name="AuthorId">$5$</Attr>
      <Attr Name="CategoryId">$7$</Attr>
     </AttrList>

其中$$中间为数组下标。

public static string ReplaceDataByArray(ArrayList array, string strInfo)
  {
   string regexTest = "\\$\\d+\\$";
   if (Regex.IsMatch(strInfo, regexTest))
   {
    MatchCollection results = Regex.Matches(strInfo, regexTest);
    for (int i = 0; i < results.Count; i++)
    {
     string nowPatten = results[i].Value;
     regexTest = "\\$";
     int nowIndex =Convert.ToInt32(Regex.Replace(nowPatten, regexTest, ""));
     if (nowIndex < array.Count)
     {
      strInfo = strInfo.Replace(nowPatten, array[nowIndex].ToString());
     }
    }
   }
   return strInfo;
  }