【问题标题】:C# String Remove characters between two charactersC# String 删除两个字符之间的字符
【发布时间】:2021-11-06 21:41:55
【问题描述】:

例如我有字符串 Like

"//RemoveFromhere
 <div>
 <p>my name is blawal i want to remove this div </p>
  </div>
//RemoveTohere"

我想使用//RemoveFromhere 作为起点 和//RemoveTohere 作为我要删除的所有字符之间的结束点

【问题讨论】:

标签: c# html asp.net string


【解决方案1】:
  var sin = "BEFORE//RemoveFromhere"+
    "<div>"+
    "<p>my name is blawal i want to remove this div </p>"+
    "</div>"+
    "//RemoveTohereAFTER";
  const string fromId = "//RemoveFromhere";
  const string toId = "//RemoveTohere";
  var from = sin.IndexOf(fromId) + fromId.Length;
  var to = sin.IndexOf(toId);
  if (from > -1 && to > from)
    Console.WriteLine(sin.Remove(from , to - from));
//OR to exclude the from/to tags
  from = sin.IndexOf(fromId);
  to = sin.IndexOf(toId) + toId.Length;
  Console.WriteLine(sin.Remove(from , to - from));

这会给出结果 BEFORE//RemoveFromhere//RemoveTohereAFTERBEFOREAFTER

另请参阅在接​​受此答案后添加的使用来自 Cetin Basoz 的 regular expressions 的更一般(更好)的选项。

【讨论】:

  • 如果他有更多的文字,也许还有另一个 //Remove...//Remove... 怎么办?
  • 我只有在我有“RemoveFromhere”和“RemoveTohere”的地方
  • @blawalsarfraz,只为它的一个实例编写代码并不是一个好主意。但无论如何,这是你的代码。
  • @CetinBasoz:不错的(r)答案,被引用和投票。
【解决方案2】:
void Main()
{
    string pattern = @"\n{0,1}//RemoveFromhere(.|\n)*?//RemoveTohere\n{0,1}";
    var result = Regex.Replace(sample, pattern, "");
    Console.WriteLine(result);
}

static string sample = @"Here
//RemoveFromhere
 <div>
 <p>my name is blawal i want to remove this div </p>
  </div>
//RemoveTohere
Keep this.
//RemoveFromhere
 <div>
 <p>my name is blawal i want to remove this div </p>
  </div>
//RemoveTohere
Keep this too.
";

【讨论】:

    猜你喜欢
    • 2016-07-01
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 2017-10-24
    • 1970-01-01
    相关资源
    最近更新 更多