【发布时间】:2015-10-09 14:45:34
【问题描述】:
我有一个函数 ReplaceParameters,它使用 Regex.Replace 替换字符串中的值。这一直工作正常,但现在获取替换字符串的 api 已变为仅异步。这是当前代码的复制:
public static string ReplaceParameters(string query)
{
var result = Regex.Replace(query, @"(?<parameter>\|\w+\|)", ReplaceParameterEvaluator,
RegexOptions.ExplicitCapture);
return result;
}
private static string ReplaceParameterEvaluator(Match parameterMatch)
{
var parameter = parameterMatch.Groups["parameter"].Value;
return GetReplacement(parameter);
}
private static string GetReplacement(string parameter)
{
//...
}
由于(新)GetReplacement 函数现在返回的是 Task 而不是字符串:private static async Task<string> GetReplacementAsync(string parameter) ReplaceParameterEvaluator 函数无法与 MatchEvaluator 委托兼容。
由于这必须在网络服务器上运行并且不会导致死锁,我不能使用任何肮脏的异步同步黑客,例如:(使用 .Result)var replacedQuery = Regex.Replace(query, @"(?<parameter>\|\w+\|)", match => ReplaceParameterEvaluatorAsync(match).Result, RegexOptions.ExplicitCapture);
是否可以重写函数以查找所有文本,然后替换它们?可以以某种方式使用 Regex.Matches 吗?
(说真的,为什么没有 Regex.ReplaceAsync 函数??)
【问题讨论】:
-
不要使用
GetReplacementAsync或使用“hacks”。这里没有优雅的解决方案。 -
发布后我发现osdn.jp/projects/opentween/scm/git/open-tween/blobs/master/… - 其中包含 RegexAsync.ReplaceAsync 的简单实现。但它不支持捕获组。也许在我的情况下可以使用类似的方法?
-
好像先匹配一切,然后异步查找替换,然后替换一切。它使用了两次正则表达式,但是是的,这可能是可能的。
-
没有
Regex.ReplaceAsync函数,因为字符串替换不是 I/O 绑定操作,公开异步 API 没有意义。
标签: c# regex async-await