2

我有一个字符串,我想删除一个短语之前的所有内容,然后删除另一个短语之后的所有内容。IE,

myString = "words words words FIRSTPHRASE these words I want SECONDPHRASE but not these words"

所以新的字符串是"these words I want".

4

2 回答 2

3

使用 String.Substringand 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);
}

Demonstration

于 2013-10-27T22:41:32.143 回答
1

像这样的东西?

string theWordsIWant = Regex.Replace(myString, @"^.*?FIRSTPHRASE\s*(.*?)\s*SECONDPHRASE.*$", "$1");

Demonstration

于 2013-10-27T22:41:04.237 回答