我有一个字符串,我想删除一个短语之前的所有内容,然后删除另一个短语之后的所有内容。IE,
myString = "words words words FIRSTPHRASE these words I want SECONDPHRASE but not these words"
所以新的字符串是"these words I want"
.
使用 String.Substring
and String.IndexOf
,它还有一个带有起始索引的重载:
string myString = "words words words FIRSTPHRASE these words I want SECONDPHRASE but not these words";
string result = myString;
int indexOfFirstPhrase = myString.IndexOf("FIRSTPHRASE");
if(indexOfFirstPhrase >= 0)
{
indexOfFirstPhrase += "FIRSTPHRASE".Length;
int indexOfSecondPhrase = myString.IndexOf("SECONDPHRASE", indexOfFirstPhrase);
if (indexOfSecondPhrase >= 0)
result = myString.Substring(indexOfFirstPhrase, indexOfSecondPhrase - indexOfFirstPhrase);
else
result = myString.Substring(indexOfFirstPhrase);
}
像这样的东西?
string theWordsIWant = Regex.Replace(myString, @"^.*?FIRSTPHRASE\s*(.*?)\s*SECONDPHRASE.*$", "$1");