使用格式模板解析字符串? [英] Parse string using format template?

查看:145
本文介绍了使用格式模板解析字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我可以用格式化字符串

If I can format a string using

string.Format("my {0} template {1} here", 1, 2)

我可以逆转这一过程 - 我公司提供的模板,填充的字符串,.NET回报为arg0,ARG1等

can I reverse the process - I provide the template and a filled-in string, .net returns arg0, arg1, etc.?

推荐答案

有没有优雅的方式来扭转格式化字符串。但是,如果你想要一个简单的功能,你可以试试这个。

There's no elegant way to reverse the formatted string. But you can try this if you want a simple function.

private List<string> reverseStringFormat(string template, string str)
{
    string pattern = "^" + Regex.Replace(template, @"\{[0-9]+\}", "(.*?)") + "$";

    Regex r = new Regex(pattern);
    Match m = r.Match(str);

    List<string> ret = new List<string>();

    for (int i = 1; i < m.Groups.Count; i++)
    {
        ret.Add(m.Groups[i].Value);
    }

    return ret;
}

这篇关于使用格式模板解析字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆