当前位置: 代码迷 >> Web前端 >> 正则表达式,一次性美
  详细解决方案

正则表达式,一次性美

热度:90   发布时间:2012-11-05 09:35:12.0
正则表达式,一次性好
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 "";                   
        }
    }
}