<body>
<div>这里是要取出的文本A<img src=""/>这里是要取出的文本B<a href="">超链接里的文本不取出</a>这里是要取出的文本C</div>
<body>
现在我要取出:这里是要取出的文本A,这里是要取出的文本B,这里是要取出的文本C
这个正则表达式要怎么写呢?超链接中的文本不取出

解决方案 »

  1.   

    搞Java的,路过此地,献丑了……思路:
    为了简单,正则表达式中不排除超链接,但其会获取标签的名字。
    然后在代码中对标签名字进行判断,如果是超链接中的文本则不输出。
    不知此思路是否满足楼主要求?代码: static void Main(string[] args)
    {
    String s = @"<Body> 
    <div>这里是要取出的文本A <img src=""/>这里是要取出的文本B <a href="">超链接里的文本不取出 </a>这里是要取出的文本C </div> 
    <body>";
    Regex regex = new Regex( "(/?\\w+)[^>]*>([^<]*)<", RegexOptions.IgnoreCase );

    MatchCollection ms = regex.Matches( s );

    foreach( Match m in ms )
    {
    string tagName = m.Groups[1].Value.ToLower();
    string text = m.Groups[2].Value.Trim();
    if( tagName != "a" && text.Length > 0 )
    Console.WriteLine( text );
    }
    }
    结果:
    这里是要取出的文本A
    这里是要取出的文本B
    这里是要取出的文本C
      

  2.   

    能……
    代码如下: String s = @"<Body> <a href="">超链接里的文本不取出 </a>
    <div>这里是要取出的文本A <img src=""/>这里是要取出的文本B <a href="">超链接里的文本不取出 </a><a href="">超链接里的文本不取出 </a>这里是要取出的文本C <a href="">超链接里的文本不取出 </a></div> 
    <body>";
    Regex regex = new Regex( ">([^<]*)(>?<a[^<]*</a)*", RegexOptions.IgnoreCase ); MatchCollection ms = regex.Matches( s ); foreach( Match m in ms )
    {
    string text = m.Groups[1].Value.Trim();
    if( text.Length > 0 )
    {
    Console.WriteLine( m.Groups[1] );
    }
    }
      

  3.   

    全部在正则里判断就是了
    String test = @"<Body> <a href="">超链接里的文本不取出</a>
    <div>这里是要取出的文本A <img src=""/>这里是要取出的文本B <a href="">超链接里的文本不取出</a><a href="">超链接里的文本不取出</a>这里是要取出的文本C <a href="">超链接里的文本不取出</a></div> 
    <body>";
    MatchCollection mc = Regex.Matches(test, @"(?<=<(?!a)[^>]*>|^)(?!\s+<)[^<>]+(?=<(?!/a)[^>]*>|$)", RegexOptions.IgnoreCase);
    foreach (Match m in mc)
    {
        Console.WriteLine(m.Value);
    }
    Console.ReadLine();