我想写一个方法,参数为待匹配的html,如参数可能是:{jdoc:include type=""aa"" name=""bb""} ,也可能是{jdoc:include type=""aa"" name=""bb"" style=""cc""},还可能是{jdoc:include type=""aa"" name=""bb"" style=""cc"" headerLevel=""dd"" },也就是说,标签的属性是不确定的,我要把参数里的属性值取到,正则表达式得怎么写?如正则表达式:
string strHTML = @"{jdoc:include type=""aa"" name=""bb""}";
//string strHTML = @"{jdoc:include type=""aa"" name=""bb"" style=""cc""}";
//string strHTML=@"{jdoc:include type=""aa"" name=""bb"" style=""cc"" headerLevel=""dd"" }";Match m = Regex.Match(strHTML, @"{jdoc:.*? name=""(?<name>[^""]+)"" }|style=""(?<style>[^""]+)""");
//也不对啊
Console.WriteLine(m.Groups["name"].value);

解决方案 »

  1.   

    public static void Main(string[] args)
            {
                string strs = null;
                //string strHTML = @"{jdoc:include type=""aa"" name=""bb""}";
                //string strHTML = @"{jdoc:include type=""aa"" name=""bb"" style=""cc""}";
                string strHTML = @"{jdoc:include type=""aa"" name=""bb"" style=""cc"" headerLevel=""dd"" }";
                Regex r = new Regex("\"[^\"]*\"", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                foreach (Match m in r.Matches(strHTML))
                {
                    foreach (Capture c in m.Captures)
                    {
                        strs += c.Value;
                    }
                }
                Console.WriteLine(strs);
                Console.ReadKey();
            }
      

  2.   

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Collections;
    using System.Xml.Linq;namespace ConsoleCSharp
    {
        class Program
        {        static void Main(string[] args)
            {
                string[] str = { @"{jdoc:include type=""aa"" name=""bb""}",
                                   @"{jdoc:include type=""aa"" name=""bb"" style=""cc""}",
    @"{jdoc:include type=""aa"" name=""bb"" style=""cc"" headerLevel=""dd"" }"
    };
                Regex re = new Regex(@"{jdoc:include(\s*(?<name>[^=]*)=""(?<value>[^""]*)"")*\s*}");            foreach (string s in str)
                {
                    Console.WriteLine("------------------------");
                    MatchCollection mc = re.Matches(s);
                    foreach (Match m in mc)
                    {
                        int count = m.Groups["name"].Captures.Count;
                        for (int i = 0; i < count; i++)
                        {
                            Console.WriteLine("{0} {1}", m.Groups["name"].Captures[i].Value, m.Groups["value"].Captures[i].Value);
                        }
                            
                    }
                }
            }
        }
    }