Replace 替换指定位置的通配符

            string statement = "as1{lead}1dfasdfabcdefjhij2{lead}2klmnopqrstuvwxyz3{lead}3aasdfasd4{lead}4f";


            //要求 :写出自定义的Replace方法替换第x个通配符{lead}出现的位置 
            //方法定义:Replace(string str,string pattern,string newstr,int index )

            //结果 
            //调用方法 Replace(statement,"{lead}"," first ",1)    结果"as1 first 1dfasdfabcdefjhij2{lead}2klmnopqrstuvwxyz3{lead}3aasdfasd4{lead}4f"
            //调用方法 Replace(statement,"{lead}"," third ",3)    结果"as1 first 1dfasdfabcdefjhij2{lead}2klmnopqrstuvwxyz3 third 3aasdfasd4{lead}4f"


方法一:

static string Replace(string str, string pattern, string newstr, int index)
        {
            int leadListIndex = 0;
            return Regex.Replace(str, Regex.Escape(pattern), m =>
            {
                if (++leadListIndex == index)
                    return newstr; 
                return m.Value;
            });
        }

        //精简后
        string Replace(string str, string pattern, string newstr, int index)
        {
            int leadListIndex = 0;
            return Regex.Replace(str, Regex.Escape(pattern), m => ++leadListIndex == index ? newstr : m.Value);
        }

 

方法二:

public static string GetRePlaceStr(string str, string pattern, string newstr, int index = 1)
        {
            Regex reg = new Regex(pattern);
            //查询匹配数量           
            var t = reg.Matches(str);
            return reg.Replace(str, newstr, 1, t[index - 1].Index);
        }


 

发帖求助地址:
http://bbs.csdn.net/topics/390848935?page=1#post-397896822

posted @ 2014-08-01 15:35  振乾  阅读(963)  评论(0)    收藏  举报