gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:41:44 28 4
gpt4 key购买 nike

如果我可以使用

格式化字符串
string.Format("my {0} template {1} here", 1, 2)

我可以颠倒这个过程吗 - 我提供模板和填充的字符串,.net 返回 arg0、arg1 等?

最佳答案

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

private List<string> reverseStringFormat(string template, string str)
{
//Handles regex special characters.
template = Regex.Replace(template, @"[\\\^\$\.\|\?\*\+\(\)]", m => "\\"
+ m.Value);

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

关于c# - 使用格式模板解析字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5346158/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com