删除特定短语之前和特定短语之后的字符串中的所有内容

时间:2013-10-27 22:35:04

标签: c# string

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

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

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

2 个答案:

答案 0 :(得分:3)

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

Demonstration

答案 1 :(得分:1)

这样的东西?

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

Demonstration