使用正则表达式,进行批量修改字符串中的匹配内容

网上保存了好多html页面回来,发现其中的样式、图片等都不能正常显示,比如:原图片地址为href="css/css.css"    和src="images/bg.gif",代码中存在很多这样的字符串段,当然图片名字是不一样的。假设网站地址为http://www.website.com

我想html页面代码中的所有类似的字符串加上http://www.website.com/,比如修改后为href="http://www.website.com/css/css.css"     src="http://www.website.com/images/bg.gif", 等

调用Repair方法即可:

        //修补文档内容
        private void Repair(ref string documentText)
        {
            int startIndex = 0;
            Match(ref documentText, ref startIndex);
        }
       
        private void Match(ref string documentText, ref int startIndex)
        {
            string srcReg = "src=\"[^\"]*js\"";//匹配类似“src="**"” 中间是 除了“"”之外的任意字符
            Regex regex = new Regex(srcReg);
            Match m = regex.Match(documentText, startIndex);

            string code = m.Value;

            if (startIndex < documentText.Length - 1)//如果未到达末端
            {
                int indexCode = documentText.IndexOf(code, startIndex);
                string frontCode = documentText.Substring(0, indexCode);
                string endCode = documentText.Substring(indexCode + code.Length, documentText.Length - indexCode - code.Length);

                if (code.IndexOf("http://www.website.com/") < 0)
                {
                    string[] tmp = code.Split('\"');
                    if (tmp.Length > 1)
                    {
                        code = tmp[0] + "\"http://www.website.com/" + tmp[1] + "\"";
                        documentText = frontCode + code + endCode;
                    }
                }
                startIndex = documentText.IndexOf(code, startIndex) + code.Length;

                Match(ref documentText, ref startIndex);
            }
        }

posted @ 2006-09-15 11:35  Kevin Lin  阅读(1124)  评论(1编辑  收藏  举报