码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2014-10-23 22:20:03      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   使用   for   

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 />");
                }


            }
        }
    }
}

 

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

标签:style   blog   http   color   io   os   ar   使用   for   

原文地址:http://www.cnblogs.com/zoro-zero/p/4046947.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!