首页 > 解决方案 > 在C#中给定字符串段落之前和之后删除字符串

问题描述

我在这里有一个示例段落:

var story = "Once upon a time, there was a little girl named <i>Goldilocks.</i>
She went for a walk in the forest. Pretty soon, she came upon a house. <strong>She 
knocked and, when no one answered, </strong>she walked right in. At the table in the kitchen, 
there were three bowls of porridge. Goldilocks was hungry. She tasted the porridge from the first bowl.";

我想要做的是在某些选定字符之前和之后修剪或删除某些段落。这个特定的段落在html 标记之后</i>和之前。<strong>到目前为止,我尝试使用Substring

story.Substring(story.IndexOf("<strong>"));

但它会在<strong>我想要达到的结果之前删除所有内容,如下所示:

var story = "Once upon a time, there was a little girl named <i>Goldilocks.</i><strong>She 
knocked and, when no one answered, </strong>she walked right in. At the table in the kitchen, 
there were three bowls of porridge. Goldilocks was hungry. She tasted the porridge from the first bowl.";

没有She went for a walk in the forest. Pretty soon, she came upon a house.

这个我也试过

story = story.Substring(story.IndexOf("</i>")).Substring(0, story.LastIndexOf("<strong>" + 1);

但它不起作用。

有什么帮助吗?

标签: c#stringsubstring

解决方案


您可以使用正则表达式来实现您的组并进行高级替换。尝试这个:

Regex.Replace(story, "</i>.*?<strong>", "</i><strong>");

推荐阅读