且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用格式模板解析字符串?

更新时间:2022-01-07 04:29:40

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

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;
}