如何删除C#中包含在括号内的部分字符串?

时间:2012-07-11 10:16:27

标签: c# string

  

可能重复:
  How do I extract a string of text that lies between two (brackets) using .NET?

任何人都可以帮忙删除括在括号中的部分字符串吗?

例如,我有一个从html / xml解析出来的字符串,因此一些注释保留在字符串中,如下所示,

"hello <!-- this is not meant to be here --> world, please help me"

我想删除包含<!--, words, and -->的所有评论,并留下“hello world,please help me”

谢谢!

3 个答案:

答案 0 :(得分:4)

使用正则表达式;

 string x ="hello <!-- this is not meant to be here --> world, please help me";
 string y = Regex.Replace(x, "<!--.*?-->", "");

答案 1 :(得分:1)

string text = "hello <!-- this is not meant to be here --> world, please help me";

int start = text.IndexOf("<!--");
int end = text.IndexOf("-->") - "-->".Length;

string cleanText = text.Remove(start, end);

答案 2 :(得分:0)

使用正则表达式。

using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var regex = new Regex("[<][^<]*[>]"); // or "[<]!--[^<]*--[>]"
            var input = "hello <!-- this is not meant to be here --> world, please help me";
            var output = regex.Replace(input, String.Empty); // hello  world, please help me
        }
    }
}

此正则表达式模式 - [<][^<]*[>] - 表示:

  • 打开方括号 - [&lt;]

  • 然后任何数字(*)的字符不是空方括号 - [^&lt;]

  • 最后,关闭方括号 - [&gt;]

regex.Replace(input, String.Empty); - 这意味着:将所有与上述模式匹配的子串替换为空字符串。