简体   繁体   中英

Remove part of a string between an start and end

Code first:

   string myString = "<at>onePossibleName</at> some question here regarding <at>disPossibleName</at>"
    // some code to handle myString and save it in myEditedString
    Console.WriteLine(myEditedString);
    //output now is: some question here regarding <at>disPossibleName</at>

I want to remove <at>onePossibleName</at> from myString. The string onePossibleName and disPossbileName could be any other string.

So far I am working with

string myEditedString = string.Join(" ", myString.Split(' ').Skip(1));

The problem here would be that if onePossibleName becomes one Possible Name .

Same goes for the try with myString.Remove(startIndex, count) - this is not the solution.

There will be different method depending on what you want, you can go with a IndexOf and a SubString, regex would be a solution too.

// SubString and IndexOf method
// Usefull if you don't care of the word in the at tag, and you want to remove the first at tag
if (myString.Contains("</at>"))
{
    var myEditedString = myString.Substring(myString.IndexOf("</at>") + 5);
}
// Regex method
var stringToRemove = "onePossibleName";
var rgx = new Regex($"<at>{stringToRemove}</at>");
var myEditedString = rgx.Replace(myString, string.Empty, 1); // The 1 precise that only the first occurrence will be replaced

You could use this generic regular expression.

var myString = "<at>onePossibleName</at> some question here regarding <at>disPossibleName</at>";
var rg = new Regex(@"<at>(.*?)<\/at>");
var result = rg.Replace(myString, "").Trim();

This would remove all 'at' tags and the content between. The Trim() call is to remove any white space at the beginning/end of the string after the replacement.

string myString = "<at>onePossibleName</at> some question here regarding <at>disPossibleName</at>"

int sFrom = myString.IndexOf("<at>") + "<at>".Length;
int sTo = myString.IndexOf("</at>");

string myEditedString = myString.SubString(sFrom, sFrom - sTo);
Console.WriteLine(myEditedString);
//output now is: some question here regarding <at>disPossibleName</at>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM