删除Scriptlet<%some text here%>来自C#中字符串的标签

时间:2017-03-31 09:37:15

标签: c# regex string replace

我们如何从字符串中删除所有scriptlet标记,即&lt;% 此处的某些文本 %&gt; 。示例字符串:this is a string <% test text %> containing scriptlet tags <% test text %> how to remove all the tags with the text inside.

2 个答案:

答案 0 :(得分:2)

您可以使用正则表达式来实现此目的。 Regex.Replace方法会为您执行此操作。

var text = "<% test text %> containing scriptlet tags <% test text %> how to remove all the tags with the text inside.";
var pattern = "<%[^>]*%>";
var regex = new Regex(pattern);
var result = regex.Replace(text, string.Empty);

这将导致

  

包含scriptlet标记如何删除内部文本的所有标记。

如果您想测试和/或了解有关正则表达式的更多信息,请查看regexr

答案 1 :(得分:1)

你可以试试这个正则表达式:

<%[^%>]*%>

<强>说明: 正则表达式查找以<%开头并后跟(除%>之外的任何字符)并以%>结尾的所有字符串。

像这样使用:

string result = new Regex("<%[^%>]*%>").Replace(sampleStr, string.Empty);

<强>试验:

sample1: "This is a string <%with_tag%> and tag <%new_tag%>."
result1: "This is a string  and tag ."

sample2: "This is a string <%with_tag%>tag%> and tag <%new_tag%>."
result2: "This is a string tag%> and tag ."

此外,请注意,这并不会清除额外的<space>,尤其是当有很多连续标签时。

sampleStr: "This is a string <%with_tag%>tag%> and <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%>tag <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%>."
result: "This is a string tag%> and     tag      ."

你可以使用另一个正则表达式(如果表现真的不重要):

result = new Regex("\s{2,}").Replace(result, " ");

这样:

string sampleStr = "This is a string <%with_tag%>tag%> and <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%> <%new_tag%>tag <%new_tag%>.";
string result = new Regex("<%[^%>]*%>").Replace(sampleStr, string.Empty);
result = new Regex("\s{2,}").Replace(result, " ");

如果您考虑效果,请检查post