在C#中如何从字符串中删除以'<'开头以'>'结尾的内容?我知道可以使用正则表达式来实现,但我不太擅长。
string tagPattern = @"<[!--\W*?]*?[/]*?\w+.*?>";
I used it like this
MatchCollection matches = Regex.Matches(input, tagPattern);
foreach (Match match in matches)
{
input = input.Replace(match.Value, string.Empty);
}
它可能需要进行修改,以正确处理脚本或样式标签。
[!--\W*?]
的含义是“匹配在!
和-
之间的字符、一个非单词字符、一个*
或一个?
”。由于该组是可选的,因此它不会对负预测的明显预期目的产生任何影响(应该是(?!--)
),\W*?
和随后的*?
根本没有任何意义。 - Tim Pietzcker非正则表达式选项:但它仍然无法解析嵌套标签!
public static string StripHTML(string line)
{
int finished = 0;
int beginStrip;
int endStrip;
finished = line.IndexOf('<');
while (finished != -1)
{
beginStrip = line.IndexOf('<');
endStrip = line.IndexOf('>', beginStrip + 1);
line = line.Remove(beginStrip, (endStrip + 1) - beginStrip);
finished = line.IndexOf('<');
}
return line;
}
另一个比正则表达式快8倍的非正则代码:
public static string StripTagsCharArray(string source)
{
char[] array = new char[source.Length];
int arrayIndex = 0;
bool inside = false;
for (int i = 0; i < source.Length; i++)
{
char let = source[i];
if (let == '<')
{
inside = true;
continue;
}
if (let == '>')
{
inside = false;
continue;
}
if (!inside)
{
array[arrayIndex] = let;
arrayIndex++;
}
}
return new string(array, 0, arrayIndex);
}