2011-04-27 71 views

回答

1

您可以使用正則表達式和逆序。

var replaceHello = "ABC hello 123 hello 456 hello 789"; 
var fixedUp = Regex.Replace(replaceHello, "(?<=hello.*)hello", "goodbye"); 

這將用「再見」替換「再見」這個詞的所有例子,除了第一個例外。

+0

+1的解決方案。它是有益的。謝謝 – 2011-04-27 04:19:15

0

Regex版本簡潔,但如果您不是那種使用正則表達式的人,則可以考慮更多的代碼。

StringBuilder類提供了一種在給定子字符串內進行替換的方法。在string的擴展方法中,我們將指定一個從第一個適用匹配結束時開始的子字符串。針對論據的一些基本驗證已到位,但我不能說我已經測試過所有組合。

public static string SkipReplace(this string input, string oldValue, string newValue) 
{ 
    if (input == null) 
     throw new ArgumentNullException("input"); 

    if (string.IsNullOrEmpty(oldValue)) 
     throw new ArgumentException("oldValue"); 

    if (newValue == null) 
     throw new ArgumentNullException("newValue"); 

    int index = input.IndexOf(oldValue); 

    if (index > -1) 
    { 
     int startingPoint = index + oldValue.Length; 
     int count = input.Length - startingPoint; 
     StringBuilder builder = new StringBuilder(input); 
     builder.Replace(oldValue, newValue, startingPoint, count); 

     return builder.ToString(); 
    } 

    return input; 
} 

使用它:

string foobar = "foofoo".SkipReplace("foo", "bar");