如果我可以使用格式化字符串
string.Format("my {0} template {1} here", 1, 2)
Run Code Online (Sandbox Code Playgroud)
我可以反转过程 - 我提供模板和填充字符串,.net返回arg0,arg1等?
Mik*_*ark 30
没有优雅的方法来反转格式化的字符串.但是如果你想要一个简单的功能,你可以尝试这个.
private List<string> reverseStringFormat(string template, string str)
{
//Handels 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;
}
Run Code Online (Sandbox Code Playgroud)
在一般情况下,String.Format是不可逆的.
如果只有一个{0},则可以编写至少提取值的字符串表示形式的通用代码.你绝对不能反转它来生成原始对象.
样品:
多个参数:string.Format("my{0}{1}", "aa", "aaa");
产生"myaaaaa",反转string.ReverseFormat("my{0}{1}", "myaaaaa")
必须决定如何在没有任何信息的情况下分割2中的"aaaaa"部分.
string.Format("{0:yyyy}", DateTime.Now);
2011年无法逆转数据类型的结果,大多数关于价值的信息本身都丢失了.
一种方法是使用正则表达式。对于您的示例,您可以这样做:
Regex regex = new Regex("^my (.*?) template (.*?) here$");
Match match = regex.Match("my 53 template 22 here");
string arg0 = match.Groups[1].Value; // = "53"
string arg1 = match.Groups[2].Value; // = "22"
Run Code Online (Sandbox Code Playgroud)
基于这种技术,编写一个扩展方法来完全完成您想要的操作并不困难。
只是为了好玩,这是我的第一次天真的尝试。我还没有测试过这个,但应该很接近。
public static object[] ExtractFormatParameters(this string sourceString, string formatString)
{
Regex placeHolderRegex = new Regex(@"\{(\d+)\}");
Regex formatRegex = new Regex(placeHolderRegex.Replace(formatString, m => "(<" + m.Groups[1].Value + ">.*?)");
Match match = formatRegex.Match(sourceString);
if (match.Success)
{
var output = new object[match.Groups.Count-1];
for (int i = 0; i < output.Length; i++)
output[i] = match.Groups[i+1].Value;
return output;
}
return new object[];
}
Run Code Online (Sandbox Code Playgroud)
这将允许你做
object[] args = sourceString.ExtractFormatParameters("my {0} template {1} here");
Run Code Online (Sandbox Code Playgroud)
该方法非常幼稚,有很多问题,但它基本上会找到格式表达式中的任何占位符,并在源字符串中找到相应的文本。它将为您提供与从左到右列出的占位符相对应的值,而不参考序数或占位符中指定的任何格式。可以添加此功能。
另一个问题是格式字符串中的任何特殊正则表达式字符都会导致该方法失败。需要对 进行更多处理,formatRegex
以转义属于 的任何特殊字符formatString
。
归档时间: |
|
查看次数: |
22043 次 |
最近记录: |