我有一个字符串,我想删除一个短语之前的所有内容,然后删除一个不同的短语之后的所有内容。即,
myString = "words words words FIRSTPHRASE these words I want SECONDPHRASE but not these words"
所以新字符串将是"these words I want"
。
答案 0 :(得分:3)
使用String.Substring
和String.IndexOf
,它还有一个带有起始索引的overload:
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);
}
答案 1 :(得分:1)
这样的东西?
string theWordsIWant = Regex.Replace(myString, @"^.*?FIRSTPHRASE\s*(.*?)\s*SECONDPHRASE.*$", "$1");