gpt4 book ai didi

c# - 正则表达式替换 : how to get length of the match dynamically in replacement

转载 作者:行者123 更新时间:2023-11-30 22:58:48 25 4
gpt4 key购买 nike

有没有办法用匹配中找到的相同长度的字符替换匹配表达式?在下面的代码中更容易理解:

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();

最佳答案

这应该有效:

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

关于c# - 正则表达式替换 : how to get length of the match dynamically in replacement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52711856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com