If I can format a string using
string.Format("my {0} template {1} here", 1, 2)
can I reverse the process - I provide the template and a filled-in string, .net returns arg0, arg1, etc.?
The Python string Template is created by passing the template string to its constructor. It supports $-based substitutions. This class has 2 key methods: substitute(mapping, **kwds): This method performs substitutions using a dictionary with a process similar to key-based mapping objects.
The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value. The following Python code illustrates the way of performing string formatting.
What is toString()? A toString() is an in-built method in Java that returns the value given to it in string format. Hence, any object that this method is applied on, will then be returned as a string object.
String parsing in java can be done by using a wrapper class. Using the Split method, a String can be converted to an array by passing the delimiter to the split method. The split method is one of the methods of the wrapper class. String parsing can also be done through StringTokenizer.
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) { //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; }
String.Format is not reversable in general case.
If you have exactly one {0} it is actaully possible to write generic code that at least extract string representation of the value. You definitely can't reverse it to produce original objects.
Samples:
Multiple arguments: string.Format("my{0}{1}", "aa", "aaa");
produces "myaaaaa", tring to reverse string.ReverseFormat("my{0}{1}", "myaaaaa")
have to decide how to split "aaaaa" portion in 2 without any information.
Inability to reverse to data type string.Format("{0:yyyy}", DateTime.Now);
results in 2011, most of information about value itself lost.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With