首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

正则表达式,一次性美

2012-11-05 
正则表达式,一次性好using Systemusing System.Text.RegularExpressionsclass Program{static void Main

正则表达式,一次性好
using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main(string[] args)
    {
        string str = "<You're angle & evil>";
        string pattern = "'|&|<|>";

        Regex regex = new Regex(pattern);

        Program prog = new Program();
        MatchEvaluator evaluator = new MatchEvaluator(prog.ConvertToXML);
        Console.WriteLine(regex.Replace(str, evaluator));
        Console.Read();
    }

    //把正则表达式的匹配到的字符转换成xml能正常识别的标识
    public string ConvertToXML(Match m)
    {
               //string s0=m.Groups[0].Value;
           //string s1=m.Groups[1].Value;
           //string s2=m.Groups[2].Value;
        switch (m.Value)
        {
            case "'":
                return "&apos";
            case "&":
                return "&amp";
            case "<":
                return "&lt";
            case ">":
                return "&gt";
            default:
                return "";                   
        }
    }
}

热点排行