[英]Remove part of a string between an start and end
代碼優先:
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>
我想從myString中刪除<at>onePossibleName</at>
。 字符串onePossibleName
和disPossbileName
可以是任何其他字符串。
到目前為止,我正在與
string myEditedString = string.Join(" ", myString.Split(' ').Skip(1));
這里的問題是,如果onePossibleName
成為one Possible Name
。
嘗試使用myString.Remove(startIndex, count)
-這不是解決方案。
根據您的需要會有不同的方法,可以使用IndexOf和SubString,正則表達式也可以解決。
// 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
您可以使用此通用正則表達式。
var myString = "<at>onePossibleName</at> some question here regarding <at>disPossibleName</at>";
var rg = new Regex(@"<at>(.*?)<\/at>");
var result = rg.Replace(myString, "").Trim();
這將刪除所有“ at”標簽及其之間的內容。 Trim()
調用是在替換后刪除字符串開頭/結尾的所有空格。
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.