2011-04-27 69 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");