繁体   English   中英

从具有条件的字符串中删除特殊字符

[英]Remove special characters from a string with a condition

我有一个字符串如下 -

"This is <h2>a place/h2>
<p>You know its a good place!</p>
<ul>
    <li>Booked your ticket #20130114074912_AN3P703C on Monday, January 14</li>
</ul>"

所以,我希望我的字符串如下

"This is a place
You know its a good place.
Booked your ticket #20130114074912_AN3P703C on Monday, January 14"

我相信这是你的答案。 链接

尝试这个:

// <summary>
/// Remove HTML from string with Regex.
/// </summary>
public static string StripTagsRegex(string source)
{
   return Regex.Replace(source, "<.*?>", string.Empty);
}

输出:

Input:    <p>The <b>dog</b> is <i>cute</i>.</p>
Output:   The dog is cute.

您可以使用以下方法从任何字符串中删除HTML标记

static string StripHTML (string inputString)
{
  return Regex.Replace(inputString, "<.*?>", string.Empty);
}

这样就可以完成你的工作

String neededString = Regex.Replace(source, "<.*?>", string.Empty);

对于更多comcplicated字符串,包含CSS,JavaScript节点u可以使用以下内容

String neededStringRegex.Replace(subjectString, @"<(style|script)[^<>]*>.*?</\1>|</?[a-z][a-z0-9]*[^<>]*>|<!--.*?-->", "")

下载并引用HTML Agility Pack ,然后调用以下内容:

var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(input);
string output = htmlDoc.DocumentNode.InnerText;

这仍然不会删除你的malformed /h2>标签,但它应该处理比正则表达式更多的HTML。

这应该可以解决问题

string input = "This is <h2> a place</h2><p>You know its a good place!</p><ul>    <li>Booked your ticket #20130114074912_AN3P703C on Monday, January 14</li></ul>";
input = Regex.Replace(input, "<.*?>", string.Empty);

这将找到“<>”中包含的所有字符串,并将其替换为“”或空字符串

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM