加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

变量在C#中替换为字符串

发布时间:2020-12-16 01:50:22 所属栏目:百科 来源:网络整理
导读:我有格式的字符串 “sometext%1%-%2%blablabla%15%” 和类变量的集合: public class Variable{ public long Id { get; set; } public string Value { get; set; }} 如何使用Regex.Replace替换所有子字符串,例如“%{ID Number}%”,其中Value字段为Id,其等
我有格式的字符串

“sometext%1%-%2%blablabla%15%”

和类变量的集合:

public class Variable
{
     public long Id { get; set; }
     public string Value { get; set; }
}

如何使用Regex.Replace替换所有子字符串,例如“%{ID Number}%”,其中Value字段为Id,其等于{ID Number}(例如,将“%1%”替换为ID = 1的“变量值”字段)方法或类似的东西?

解决方法

您可以使用自己的匹配评估程序.这是未经测试的,但解决方案应该与此代码类似:

String processed = Regex.Replace (rawInput,@"%(d+)%",MyMatchEvaluator);

private string MyMatchEvaluator (Match match)
{
    int id = int.Parse (match.Captures[0].Value);
    return _variables.Where(x => x.Id == id).Value;
}

_variables是你的变量集合,rawInput是你的输入字符串.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读