【发布时间】:2019-01-24 06:37:59
【问题描述】:
我尝试在 C# 中编写一个函数来删除两个字符串之间的字符串。像这样:
string RemoveBetween(string sourceString, string startTag, string endTag)
一开始我以为这很容易,但后来我遇到了越来越多的问题
所以这是最简单的情况(所有示例都带有 startTag="Start" 和 endTag="End")
"Any Text Start remove this End between" => "Any Text StartEnd between"
但它也应该能够处理多个而不删除之间的文本:
"Any Text Start remove this End between should be still there Start and remove this End multiple" => "Any Text StartEnd between should be still there StartEnd multiple"
它应该总是用最小的字符串来删除:
"So Start followed by Start only remove this End other stuff" => "So Start followed by StartEnd other stuff"
它还应该尊重标签的顺序:
"the End before Start. Start before End is correct" => "the End before Start. StartEnd is correct"
我尝试了一个不起作用的正则表达式(它无法处理多个):
public string RemoveBetween(string sourceString, string startTag, string endTag)
{
Regex regex = new Regex(string.Format("{0}(.*){1}", Regex.Escape(startTag), Regex.Escape(endTag)));
return regex.Replace(sourceString, string.Empty);
}
然后我尝试使用 IndexOf 和 Substring,但我没有看到结束。即使它会起作用,这也不是解决这个问题的最优雅的方法。
【问题讨论】: