C# Regex正则常用方法的使用

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace test
{
    public partial class RegexTest : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //将img标签替换掉
                string imgReg = "<img.*?(?:>|\\/>)";

                string imgContent = "<img border='0' width='540px' height='260px' alt='海贼王764话专题:白色怪物' src='http://pic2.52pk.com/files/141017/1283574_1G931118.jpg'>";
                
                //创建一个正则
                Regex reg = new Regex(imgReg);
                
                //判断imgContent是否含有匹配的字符
                bool isMatch = reg.IsMatch(imgContent);

                Response.Write(isMatch +"<br />");

                Response.Write(imgContent + "<br />");

                //替换后的结果
                string result = reg.Replace(imgContent,"");

                //imgContent的内容 未改变
                Response.Write(imgContent + "<br />");

                Response.Write(result + "<br />");

                Response.Write("=============================获取匹配结果========================<br />");
                
                //获取匹配结果

                string content = "<img src='a'/>aaaa<img src='b'/>bbbb<img src='c'/>cccc";

                string pxRegStr = "px";

                Regex pxReg = new Regex(imgReg);

                //获取匹配的结果数组
                var matchs = pxReg.Matches(content);

                foreach (var item in matchs)
                {
                    Response.Write(item + "<br />");
                }

                Response.Write("=========================获取正则分割匹配结果=====================<br />");
                //使用正则分割内容
                Regex splitReg = new Regex(imgReg);

                //获取匹配的结果数组
                var results = pxReg.Split(content);

                foreach (var item in results)
                {
                    Response.Write(item + "<br />");
                }


            }
        }
    }
}

 

posted @ 2014-10-23 21:36  大空白纸  阅读(876)  评论(0编辑  收藏  举报