2013-10-27 38 views

回答

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

+0

完美的作品!謝謝! –

1

這樣的事情?

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

Demonstration

相關問題