+1  A: 

I'm not familiar with the Java regex classes, but this is my C# interpretation of what I think your code does:

private const string tempUserBlock = "%%%COMPRESS~USER{0}~{1}%%%"; 
string html = "some html"; 
int p = 0; 
var userBlock = new List<string>(); 

MatchCollection matcher = preservePattern.Matches(html); 
StringBuilder sb = new StringBuilder(); 
int last = 0;
foreach (Match m in matcher)
{
    string match = m.Groups[0].Value; 
    if(match.Trim().Length > 0) { 
        userBlock.Add(match); 
        sb.Append(html.Substring(last, m.Index - last));
        sb.Append(m.Result(string.Format(tempUserBlock, p, index++)));
    }
    last = m.Index + m.Length;
}
sb.Append(html.Substring(last);
html = sb.ToString(); 
Gabe
awesome, that is almost exactly what I came up with! You put the m.Index + m.Length in the correct place. Thanks. I'll let you know how it performs in a bit.
David Murdoch
Works perfectly. Thanks!
David Murdoch
+1  A: 

There's no need to reproduce Java's appendReplacement/appendTail functionality; .NET has something better: MatchEvaluator. Check it out:

string holder = "Element {0} = {1}";
string s0 = "111 222 XYZ";
ArrayList arr = new ArrayList();

string s1 = Regex.Replace(s0, @"\d+",
  m => string.Format(holder, arr.Add(m.Value), m.Value)
);

Console.WriteLine(s1);
foreach (string s in arr)
{
  Console.WriteLine(s);
}

output:

Element 0 = 111 Element 1 = 222 XYZ
111
222

There are several ways to implement the MatchEvaluator, all thoroughly discussed in this article. This one (lambda expressions) is by far the coolest.

Alan Moore
I'll check it out in the morning. +1 for programming based on "coolness."
David Murdoch
Excellent. This worked very well. Thank you.
David Murdoch