<body>
<div>这里是要取出的文本A<img src=""/>这里是要取出的文本B<a href="">超链接里的文本不取出</a>这里是要取出的文本C</div>
<body>
现在我要取出:这里是要取出的文本A,这里是要取出的文本B,这里是要取出的文本C
这个正则表达式要怎么写呢?超链接中的文本不取出
<div>这里是要取出的文本A<img src=""/>这里是要取出的文本B<a href="">超链接里的文本不取出</a>这里是要取出的文本C</div>
<body>
现在我要取出:这里是要取出的文本A,这里是要取出的文本B,这里是要取出的文本C
这个正则表达式要怎么写呢?超链接中的文本不取出
为了简单,正则表达式中不排除超链接,但其会获取标签的名字。
然后在代码中对标签名字进行判断,如果是超链接中的文本则不输出。
不知此思路是否满足楼主要求?代码: 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
代码如下: 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] );
}
}
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();