问题描述
|
我不知道正则表达式,仅一小部分任务,我不想坐下来学习它们,更不用说它们看起来很复杂了。我想做的是将一个段落传递给方法,并删除一段以参数“ begin”开始并以参数“ end”结束的文本。
public static string RemoveBetween(string wholeText,string begin,string end)
{
}
例如:
string myString = \"one two three four five\";
myString = RemoveBetween(myString,\"two\",\"four\");
最后的字符串将是“五分之一”
解决方法
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);
}
简单。认真学习正则表达式;他们进行了大量的分析,并将其简化为一行代码。
作为比较,这近似于没有Regex所要做的事情:
public static string RemoveBetween(string wholeText,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;
}
, 这是另一个示例,分步完成,因此更容易理解发生了什么,
public static string RemoveBetween(string wholeText,string end)
{
int indexOfBegin = wholeText.IndexOf(begin);
int IndexOfEnd = wholeText.IndexOf(end);
int lenght = IndexOfEnd + end.Length - indexOfBegin;
string removedString = wholeText.Substring(indexOfBegin,lenght);
return wholeText.Replace(removedString,\"\");
}
, 您当然不需要正则表达式,如果您不使用它们,则更容易检查输入。
public static string RemoveBetween( string wholeText,string end ) {
var beginIndex = wholeText.IndexOf( begin );
var endIndex = wholeText.IndexOf( end );
if( beginIndex < 0 || endIndex < 0 || beginIndex >= endIndex ) {
return wholeText;
}
return wholeText.Remove( beginIndex,endIndex - beginIndex + end.Length );
}
, 也许是这样。
string myString = \"one two three four five\";
myString = myString.Substring(0,myString.IndexOf(\"two\")) + myString.Substring(myString.IndexOf(\"four\") + \"four\".Length);