我有一個字符串,我想刪除短語之前的所有內容,然後刪除不同短語之後的所有內容。即刪除特定短語之前和特定短語之前的字符串中的所有內容
myString = "words words words FIRSTPHRASE these words I want SECONDPHRASE but not these words"
所以新的字符串將是"these words I want"
。
我有一個字符串,我想刪除短語之前的所有內容,然後刪除不同短語之後的所有內容。即刪除特定短語之前和特定短語之前的字符串中的所有內容
myString = "words words words FIRSTPHRASE these words I want SECONDPHRASE but not these words"
所以新的字符串將是"these words I want"
。
使用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);
}
完美的作品!謝謝! –
這樣的事情?
string theWordsIWant = Regex.Replace(myString, @"^.*?FIRSTPHRASE\s*(.*?)\s*SECONDPHRASE.*$", "$1");
沒錯我滑了一下,按回車鍵:P固定現在編輯! –