【问题标题】:C# Beginner: Delete ALL between two characters in a string (Regex?)C#初学者:删除字符串中两个字符之间的所有字符(正则表达式?)
【发布时间】:2013-12-17 06:37:59
【问题描述】:

我有一个带有 html 代码的字符串。我想删除所有 html 标签。所以 之间的所有字符。

这是我截取的代码:

WebClient wClient = new WebClient();
SourceCode = wClient.DownloadString( txtSourceURL.Text );
txtSourceCode.Text = SourceCode;
//remove here all between "<" and ">"
txtSourceCodeFormatted.Text = SourceCode;

希望有人可以帮助我

【问题讨论】:

  • 如果 &lt;&gt; 字符出现在 cmets、脚本、字符串等中怎么办?
  • 不,不要使用正则表达式来解析 HTML 字符串。一场真正的噩梦在等着你。这是 SO 中最受欢迎的答案之一。 stackoverflow.com/questions/1732348/… 最好的方法是使用专门的 HTML 解析器,例如 HTML Agility Pack
  • @Steve 我最喜欢的答案:)
  • 在这种情况下使用 .NET XML-Parser 也可能有效?还是我错了?

标签: c# regex windows


【解决方案1】:

试试这个:

txtSourceCodeFormatted.Text = Regex.Replace(SourceCode, "<.*?>", string.Empty);

但是,正如其他人提到的,handle with care

【讨论】:

  • 请注意,在极少数情况下,这可能会导致意外行为!
【解决方案2】:

根据Ravi's answer,可以使用

string noHTML = Regex.Replace(inputHTML, @"<[^>]+>|&nbsp;", "").Trim();

string noHTMLNormalised = Regex.Replace(noHTML, @"\s{2,}", " ");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-16
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    相关资源
    最近更新 更多