删除2个字符串之间的文本

时间:2018-08-17 08:50:07

标签: c# string

我试图用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"

我尝试了一个不起作用的RegEx(它不能处理倍数):

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,但是我看不到结束。即使可行,这也不是解决此问题的最优雅的方法。

5 个答案:

答案 0 :(得分:2)

这是使用hasMany

的方法
string.Remove()

我使用string input = "So Start followed by Start only remove this End other stuff"; int start = input.LastIndexOf("Start") + "Start".Length; int end = input.IndexOf("End", start); string result = input.Remove(start, end - start); 是因为可以有多个开始,而您想拥有最后一个。

答案 1 :(得分:1)

您可以使用此:

public static string Remove(string original, string firstTag, string secondTag)
{
   string pattern = firstTag + "(.*?)" + secondTag;
   Regex regex = new Regex(pattern, RegexOptions.RightToLeft);

   foreach(Match match in regex.Matches(original))
   {
      original = original.Replace(match.Groups[1].Value, string.Empty);
   }

   return original;
}

答案 2 :(得分:0)

或者您可以尝试使用LINQ,如显示的here

$(".inp-txt").bind('keyup', function(e) {
  if (e.keyCode != 17)
    console.log("Handler for keyup bind is called");
});

$(".inp-txt").bind('paste', function() {
  console.log("Handler for paste bind is called.");
});

答案 3 :(得分:0)

from selenium.webdriver.support.ui import WebDriverWait

topics_number = len(driver.find_elements_by_class_name('topics'))
more_info_button.click()
WebDriverWait(driver, 10).until(lambda driver: len(driver.find_elements_by_class_name('topics')) > topics_number)
extended_list = driver.find_elements_by_class_name('topics')

答案 4 :(得分:0)

您必须认真修改函数以与?进行非贪婪匹配。 :

    public static 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, startTag+endTag);
    }
相关问题