C# String 删除两个字符之间的字符
Posted
技术标签:
【中文标题】C# String 删除两个字符之间的字符【英文标题】:C# String Remove characters between two characters 【发布时间】: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
作为我要删除的所有字符之间的结束点
【问题讨论】:
到目前为止你有什么?请更新您的问题,以便它在 minimal, complete, and verifiable example 中显示您的相关代码。 可以使用 indexOf、RegEx.Split ... 也许这确实回答了你的问题:***.com/questions/51891661/… 这能回答你的问题吗? Remove html tags from string including   in C# 请澄清您的具体问题或提供更多详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。 【参考方案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//RemoveTohereAFTER
和 BEFOREAFTER
另请参阅在接受此答案后添加的使用来自 Cetin Basoz 的 regular expressions 的更一般(更好)的选项。
【讨论】:
如果他有更多的文字,也许还有另一个 //Remove...//Remove... 怎么办? 我只有在我有“RemoveFromhere”和“RemoveTohere”的地方 @blawalsarfraz,只为它的一个实例编写代码并不是一个好主意。但无论如何,这是你的代码。 @CetinBasoz:不错的(r)答案,被引用和投票。【参考方案2】:void Main()
string pattern = @"\n0,1//RemoveFromhere(.|\n)*?//RemoveTohere\n0,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.
";
【讨论】:
以上是关于C# String 删除两个字符之间的字符的主要内容,如果未能解决你的问题,请参考以下文章