猿问

删除字符串开头和结尾之间的部分

首先代码:


   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>

我想<at>onePossibleName</at>从 myString 中删除。该字符串onePossibleName可以disPossbileName是任何其他字符串。


到目前为止我正在与


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

这里的问题是,如果onePossibleName变成one Possible Name。


尝试也是如此myString.Remove(startIndex, count)- 这不是解决方案。


FFIVE
浏览 155回答 3
3回答

哔哔one

根据你想要的,会有不同的方法,你可以使用 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 tagif (myString.Contains("</at>")){&nbsp; &nbsp; var myEditedString = myString.Substring(myString.IndexOf("</at>") + 5);}// Regex methodvar 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

白衣非少年

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>

哆啦的时光机

您可以使用这个通用正则表达式。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()调用是在替换后删除字符串开头/结尾处的所有空格。
随时随地看视频慕课网APP
我要回答