我写了一个正则表达式用来过滤HTML代码中的所有标签,仅保留文字信息。表达式如下:
MyRule = @"<(?:.|\s)*?>";
使用该表达式过滤HTML特殊范例代码:
<td title="aaa" onmouseover="if (this.title.length > 0) {this.style.cursor='hand';}" width="128" bgcolor="#848484" height="25" >文本内容</td>理论上应该得到:文本内容
实际运行后得到:0) {this.style.cursor='hand';}" width="128" bgcolor="#848484" height="25" >文本内容大部分的标签不太会碰到这种情况,例如<td>文本内容</td>,这种情况就属于常见的,这样运行会得到正确结果前轮距(mm),而上述问题是由于标签中的事件本身包含了一个">"符号,从而导致正则表达式解析时出错。我想了很久也没想到该如何修改正则表达式来兼容这种情况。请各位大侠帮忙!我的源代码如下:
private string GetText(string Content)
{
string Result = null;
string MyRule = null;
Regex MyRegex = null;
MyRule = @"[\r\n]*<(?:.|\s)*?>";
MyRegex = new Regex(MyRule, RegexOptions.IgnoreCase);
Result = MyRegex.Replace(Content, "");
return Result;
}
MyRule = @"<(?:.|\s)*?>";
使用该表达式过滤HTML特殊范例代码:
<td title="aaa" onmouseover="if (this.title.length > 0) {this.style.cursor='hand';}" width="128" bgcolor="#848484" height="25" >文本内容</td>理论上应该得到:文本内容
实际运行后得到:0) {this.style.cursor='hand';}" width="128" bgcolor="#848484" height="25" >文本内容大部分的标签不太会碰到这种情况,例如<td>文本内容</td>,这种情况就属于常见的,这样运行会得到正确结果前轮距(mm),而上述问题是由于标签中的事件本身包含了一个">"符号,从而导致正则表达式解析时出错。我想了很久也没想到该如何修改正则表达式来兼容这种情况。请各位大侠帮忙!我的源代码如下:
private string GetText(string Content)
{
string Result = null;
string MyRule = null;
Regex MyRegex = null;
MyRule = @"[\r\n]*<(?:.|\s)*?>";
MyRegex = new Regex(MyRule, RegexOptions.IgnoreCase);
Result = MyRegex.Replace(Content, "");
return Result;
}
MyRule=@"<(?:[^><]|""[^""]""|'[^']')*>";
MyRule =
@"(?x) # 宽松排列格式
< # 开始的尖括号(<)
(?: # 下述字符
""[^""]*"" # 双引号字符串
| # 或者是 ...
'[^']*' # 单引号字符串
| # 或者是 ...
[^""'>] # 除了双引号、单引号或结束的尖括号(>)外的其他文本
)* # 重复任意多次
> # 结束的尖括号">"
";
@"(?x) # 宽松排列格式
< # 开始的尖括号(<)
(?: # 下述字符
""[^""]*"" # 双引号字符串
| # 或者是 ...
'[^']*' # 单引号字符串
| # 或者是 ...
[^""'>] # 除了双引号、单引号或结束的尖括号(>)外的其他文本
)* # 重复任意多次
> # 结束的尖括号(>)
";
MyRule=@"<(?:[^><]|""[^""]""|'[^']')*>";
// 不过仔细看,我这个也没错啊...
// MyRule=@"<(?:[^><]|""[^""]""|'[^']')*>";
// 实际检验一下:using System.Text.RegularExpressions;class Test
{
static void Main()
{
string s = @"<td onmouseover=""if (a > 0)"">abc</td>def";
string r = @"<(?:[^><]|""[^""]""|'[^']')*>";
string t = Regex.Replace(s, r, "");
Console.WriteLine(t); // 输出:“ 0)">abcdef”
}
}
MyRule=@"<(?:[^><]|""[^""]*""|'[^']*')*>";
// MyRule=@"<(?:[^><]|""[^""]*""|'[^']*')*>";
// 还是有问题:
// 因为你的“[^><]”可以匹配比引号。using System;
using System.Text.RegularExpressions;class Test
{
static void Main()
{
string s = @"<td onmouseover=""if (a > 0)"">abc</td>def";
string r = @"<(?:[^><]|""[^""]*""|'[^']*')*>";
string t = Regex.Replace(s, r, "");
Console.WriteLine(t); // 输出:“ 0)">abcdef”
}
}
string r = @"<(?:""[^""]*""|'[^']*'|[^><])*>";原来那个方案会吃掉单个引号..造成后面那些不会匹配了...