original = "[P]Hello world![/P][P style=\"LINE-HEIGHT: 9pt\"]Hello world![/P]Hello world!";
System.Text.RegularExpressions.MatchCollection MCAlign=Regex.Matches(original,@"(\[P[^\]]*\])(.[^\[]*)(\[\/P\])",RegexOptions.IgnoreCase);
for (int i=0;i<MCAlign.Count;i++)
{ hlen += MCAlign[i].Length-MCAlign[i].Groups[2].Length;
slen =MCAlign[i].Index+MCAlign[i].Length-hlen;
posite = MCAlign[i].Index+MCAlign[i].Length;
if(slen>=300)
{
return original.Substring(0,posite);
}
}
我想匹配<P xxx> </P>,我写的正则,匹配不出来,请各位指点一下,搞了好几天了,急死了

解决方案 »

  1.   


    [P style=\"LINE-HEIGHT: 9pt\"]这里末尾要不要加/P?我的写法是加的,匹配[P][/P]和[P  /P]
    \[P\][^\[\]]*\[\/P\] | \[P[^\[\]]*\/P\]匹配[P][/P]和[P /]\[P\][^\[\]]*\[\/P\] | \[P[^\[\]]*\/\] 
                                    -》这里的写法要稍微改改。看你的要求。
      

  2.   


    using System;
    using System.Text.RegularExpressions;
    using System.Text;class Test
    {
    static void Main()
    {
    string original = "[P]Hello world![/P][P style=\"LINE-HEIGHT: 9pt\"]Hello world![/P]Hello world!"; 
    MatchCollection MCAlign = Regex.Matches(original, @"(\[P[^\]]*?\])([^\[]*?)(\[\/P\])", RegexOptions.IgnoreCase); 

    for (int i = 0; i < MCAlign.Count; i++)
    {
    Console.Write(MCAlign[i].ToString());
    for (int j = 0; j < MCAlign[i].Groups.Count; j++)
    {
    Console.Write(string.Format("    {0}\n", MCAlign[i].Groups[j].Value.ToString()));
    }

    Console.WriteLine();
    }

    //Console.WriteLine(MCAlign.Count.ToString());
    Console.ReadLine();

    //不清楚下面这些代码要干什么
    // for (int i=0; i < MCAlign.Count; i++) 
    // { 
    // hlen += MCAlign[i].Length - MCAlign[i].Groups[2].Length; 
    // slen =MCAlign[i].Index+MCAlign[i].Length-hlen; 
    // posite = MCAlign[i].Index+MCAlign[i].Length; 
    // if(slen> =300) 
    // { 
    // return original.Substring(0,posite); 
    // } 
    // } 
    }
    }
      

  3.   

    用The Regulator 2.0这个工具调试一下,很好的正则调试工具
      

  4.   

    你写的正则(\[P[^\]]*\])(.[^\[]*)(\[\/P\])本身问题不大
    只是中间那个小数点在[p...]和[/p]中间为空时才会影响结果
    另外就是这种写法[p...]和[/p]中间不能嵌套其它标签
    这个用来匹配你给的例子还是没问题的,只是不知道你的for循环内的代码是用来做什么的,你说匹配不到又是哪里匹配不到