RegEx替换:如何在替换中动态获取匹配长度

时间:2018-10-09 00:46:12

标签: c# .net regex

是否可以用匹配项中找到的相同长度的字符替换匹配表达式?在下面的代码中更容易理解:

var input = "hello hellspawn, goto hell!";
var pattern = @"(hell)(?!o)";
var replacement = "****"; // is there a dynamic way to specify length here?
var replaced = Regex.Replace(input, pattern, replacement, RegexOptions.IgnoreCase);

我可以搭配火柴来做

var sbInput = new StringBuilder(input);
var sb = new StringBuilder();
var matches = Regex.Matches(input, pattern, RegexOptions.IgnoreCase);

foreach (Match match in matches) {
   sb.Length = 0;
   for (var i = 0; i < match.Length; i++) {
      sb.Append("*");
    }

    sbInput.Replace(match.Value, sb.ToString(), match.Index, match.Length);
}

var replaced = sbInput.ToString();

1 个答案:

答案 0 :(得分:2)

这应该有效:

var replaced = Regex.Replace(input, pattern,
    m => new string('*', m.Length),
    RegexOptions.IgnoreCase);