views:

43

answers:

3

Is it possible to use regex to only replace X number of occurrences of a particular string?

For example, if I have the word 'lion' in a string 10 times, could I use regex to only replace the first 6 occurences instead of all of them?

+2  A: 

I have never used it so cant speak for the validity but regex.replace has an overload that takes int count to define the number of occurences

http://msdn.microsoft.com/en-us/library/h0y2x3xs%28v=VS.90%29.aspx

Pharabus
+3  A: 

The overload that takes a "count" parameter should do what you want.

Regex cat = new Regex("cat");
string input = "cat cat cat cat cat";
Console.WriteLine(cat.Replace(input, "dog", 3));
Console.ReadLine();

The output should be: "dog dog dog cat cat"

Pat Daburu
Thanks for the example! Works perfectly!
Randy
A: 

The following code may help.

string s = "lionlionlionlionlionlionlionlionlionlion";
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("lion");
s = r.Replace(s, "donkey", 6, 0);
Console.Out.Write(s);

The output is donkeydonkeydonkeydonkeydonkeydonkeylionlionlionlion.

You can also change the replacement string dynamically as follows:

private string replaceMe(System.Text.RegularExpressions.Match m)
{
    return "donkey[" + m.Index.ToString() + "]";
}

private replaceStr() {
    string s = "lionlionlionlionlionlionlionlionlionlion";
    Regex r = new Regex("lion");
    s = r.Replace(s, new System.Text.RegularExpressions.MatchEvaluator(replaceMe),6);
    Console.Out.Write(s);
}

Then the output is donkey[0]donkey[4]donkey[8]donkey[12]donkey[16]donkey[20]lionlionlionlion.

Zafer