replace the 2nd match skipping 1st match in C# [closed]
i have a string which has 2 similar words..i want to replace the 2 secon开发者_C百科d word but not the 1st one..any help??
You could use regular expressions and a lookbehind.
var replaceHello = "ABC hello 123 hello 456 hello 789";
var fixedUp = Regex.Replace(replaceHello, "(?<=hello.*)hello", "goodbye");
This will replace all instances of the word "hello" with "goodbye", except for the first.
The Regex
version is concise, but if you're not of the sort to use a regular expression, you could consider something more code heavy.
The StringBuilder
class provides a way to replace within a given substring. In this extension method on string
, we'll specify a substring that starts at the conclusion of the first applicable match. Some basic validation against arguments are in place, but I can't say I've tested all combinations.
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;
}
Using it:
string foobar = "foofoo".SkipReplace("foo", "bar");
精彩评论