regex/linq 用计数替换连续字符

Mar*_* M. 2 c# regex linq

我有以下方法(用 C#/.NET 编写)。输入文本仅包含字母(无数字)。返回值是另一种文本,其中包含两个以上连续字符的组被替换为前面带有重复计数的字符。例如:aAAbbcccc -> aAA3b4c

public static string Pack(string text)
{
    if (string.IsNullOrEmpty(text)) return text;

    StringBuilder sb = new StringBuilder(text.Length);

    char prevChar = text[0];
    int prevCharCount = 1;

    for (int i = 1; i < text.Length; i++)
    {
        char c = text[i];
        if (c == prevChar) prevCharCount++;
        else
        {
            if (prevCharCount > 2) sb.Append(prevCharCount);
            else if (prevCharCount == 2) sb.Append(prevChar);
            sb.Append(prevChar);

            prevChar = c;
            prevCharCount = 1;
        }
    }

    if (prevCharCount > 2) sb.Append(prevCharCount);
    else if (prevCharCount == 2) sb.Append(prevChar);
    sb.Append(prevChar);

    return sb.ToString();
}
Run Code Online (Sandbox Code Playgroud)

方法不会太长。但是有人知道如何使用正则表达式以更简洁的方式做到这一点吗?还是LINQ?

Mar*_*ell 5

怎么样:

static readonly Regex re = new Regex(@"(\w)(\1){2,}", RegexOptions.Compiled);
static void Main() {
    string result = re.Replace("aAAbbbcccc",
         match => match.Length.ToString() +  match.Value[0]);   
}
Run Code Online (Sandbox Code Playgroud)

正则表达式是一个字字符,后跟相同的(back-ref)至少两次;Lamba 取匹配的长度 ( match.Length) 并附加第一个字符 ( match.Value[0])