0

可能重复:
如何使用 .NET 提取位于两个(括号)之间的文本字符串?

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

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

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

我想删除整个评论包括<!--, words, and -->,并留下“你好世界,请帮助我”

谢谢!

4

3 回答 3

4

使用正则表达式;

 string x ="hello <!-- this is not meant to be here --> world, please help me";
 string y = Regex.Replace(x, "<!--.*?-->", "");
于 2012-07-11T10:21:14.793 回答
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);
于 2012-07-11T10:26:35.527 回答
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
        }
    }
}

这个正则表达式模式 - [<][^<]*[>]- 意味着:

  • 开方括号 - [<]

  • 然后任何数量 (*) 的字符不是左方括号 - [^<]

  • 最后,结束方括号 - [>]

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

于 2012-07-11T10:20:08.753 回答