You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用正则实现Interpolate方法替换API路径中的{...}占位符?

实现字符串扩展方法Interpolate:正则式替换API路径占位符

你完全可以用正则表达式实现这个功能,相比逐次查找替换,正则能更精准定位所有占位符,还能方便做参数数量校验,减少无效API路径的生成。

代码实现(C#)

public static class StringExtensions
{
    private static readonly Regex _placeholderRegex = new Regex(@"\{[^}]+\}", RegexOptions.Compiled);

    public static string Interpolate(this string path, params object[] values)
    {
        if (path == null)
            throw new ArgumentNullException(nameof(path));
        if (values == null)
            throw new ArgumentNullException(nameof(values));

        var matches = _placeholderRegex.Matches(path).Cast<Match>().ToList();
        if (matches.Count != values.Length)
            throw new ArgumentException($"占位符数量({matches.Count})与参数数量({values.Length})不匹配", nameof(values));

        int index = 0;
        return _placeholderRegex.Replace(path, match => 
        {
            var value = values[index];
            index++;
            return value?.ToString() ?? string.Empty;
        });
    }
}

代码说明

  • 正则表达式:@"\{[^}]+\}" 会匹配所有{...}格式的占位符,不管内部包含什么内容(比如{companyId:int}这种带类型标识的也能精准匹配)
  • 参数校验:先统计占位符数量和传入参数的数量,不匹配直接抛出异常,避免生成缺省参数的无效路径
  • 替换逻辑:通过MatchEvaluator委托,每次匹配到占位符时,按顺序取出对应的参数转为字符串替换

使用示例

string pathTemplate = "/api/companies/{companyId:int}/stores/{storeKey}/products";
string interpolatedPath = pathTemplate.Interpolate(55, "se2");
// 输出结果:/api/companies/55/stores/se2/products

额外提示

  • 如果需要处理参数为null的情况,可以在替换时自定义默认值(比如返回"null"或者空字符串)
  • 正则用RegexOptions.Compiled预编译,能提升多次调用时的性能

内容的提问来源于stack exchange,提问作者Goran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 20:24:51