任何人都可以帮助删除括在括号中的字符串的一部分吗?
例如,我有一个从 html/xml 解析出来的字符串,所以一些注释保留在字符串中,如下所示,
"hello <!-- this is not meant to be here --> world, please help me"
我想删除整个评论包括<!--, words, and -->
,并留下“你好世界,请帮助我”
谢谢!
任何人都可以帮助删除括在括号中的字符串的一部分吗?
例如,我有一个从 html/xml 解析出来的字符串,所以一些注释保留在字符串中,如下所示,
"hello <!-- this is not meant to be here --> world, please help me"
我想删除整个评论包括<!--, words, and -->
,并留下“你好世界,请帮助我”
谢谢!
使用正则表达式;
string x ="hello <!-- this is not meant to be here --> world, please help me";
string y = Regex.Replace(x, "<!--.*?-->", "");
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);
使用正则表达式。
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);
- 这意味着:用空字符串替换与上述模式匹配的所有子字符串。