取消C#.NET中使用正则表达式的一段文字 [英] Remove a piece of text using Regex in C# .NET
问题描述
我不知道正恩pressions,并且只有一个小任务,我不想坐下来,学习他们 - 更不用提他们似乎很复杂。我想要做的事情是一款传递给方法,并删除与参数,将启动开始,并与参数结束结尾的一段文字。
公共静态字符串RemoveBetween(字符串wholeText,字符串开始,字符串结尾)
{
}
例如:
字符串MyString的=一二三四五;
MyString的= RemoveBetween(MyString的,二,四);
最后一个字符串将是一五
公共静态字符串RemoveBetween(字符串wholeText,字符串开始,字符串结尾)
{
Regex.Replace(wholeText,的String.Format({0} * {1}?,Regex.Escape(开始),Regex.Escape(结束))的String.Empty);
}
容易。严重的是,学会定期EX pressions;他们采取了一大堆的解析,并减少了code一行。
作为对比,这里的东西逼近你必须做没有一个正则表达式是什么:
公共静态字符串RemoveBetween(字符串wholeText,字符串开始,字符串结尾)
{
VAR的结果= wholeString;
VAR的startIndex = result.IndexOf(开始);
而(在startIndex> = 0)
{
VAR endIndex的= result.IndexOf(完)+ end.Length;
// TODO:定义行为时,结束串不出现或者是开始字符串之前的
结果= result.Substring(0,在startIndex)+ result.Substring(endIndex的+ 1,result.Length - endIndex的);
在startIndex = result.IndexOf(开始);
}
返回结果;
}
I don't know regular expressions, and for only a small task, I don't want to sit and learn them - not to mention they seem very complicated. The thing I want to do is to pass a paragraph to a method and remove a piece of text that starts with parameter "begin" and ends with parameter "end".
public static string RemoveBetween(string wholeText, string begin, string end)
{
}
Ex:
string myString = "one two three four five";
myString = RemoveBetween(myString, "two", "four");
The final string would be "one five"
public static string RemoveBetween(string wholeText, string begin, string end)
{
Regex.Replace(wholeText, String.Format("{0}.*?{1}", Regex.Escape(begin), Regex.Escape(end)), String.Empty);
}
Easy. Seriously, learn regular expressions; they take a whole lot of parsing and reduce it to a single line of code.
As a comparison, here's something approximating what you'd have to do without a Regex:
public static string RemoveBetween(string wholeText, string begin, string end)
{
var result = wholeString;
var startIndex = result.IndexOf(begin);
while(startIndex >=0)
{
var endIndex = result.IndexOf(end) + end.Length;
//TODO: Define behavior for when the end string doesn't appear or is before the begin string
result = result.Substring(0,startIndex) + result.Substring(endIndex+1, result.Length - endIndex);
startIndex = result.IndexOf(begin);
}
return result;
}
这篇关于取消C#.NET中使用正则表达式的一段文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!