Why use regex?
public static string ReplaceOccurrence(this string str, string target, string replacement, int count)
{
int pos = -1;
int counted = 0;
string result = "";
do
{
pos = (pos >= 0) ? str.IndexOf(target, pos+1) : pos = str.IndexOf(target);
if (pos >= 0)
{
counted++;
}
} while (pos >= 0 && counted != count);
if (pos >= 0)
{
result = str.Insert(pos, replacement).Remove(pos + replacement.Length, target.Length);
}
return result;
}
Usage:
string x = "(hello) (world)";
string y = "";
y = ReplaceOccurrence(x, "(", "^", 1);
y = ReplaceOccurrence(x, "(", "^", 2);
y = ReplaceOccurrence(x, ")", "^", 2);
y = ReplaceOccurrence(x, "(", "ZZZZ", 2);
y = ReplaceOccurrence(x, ")", "", 2);