Invert the Format method.
The Format
method of the String class (or equivallent, such as sprintf
) is available in most languages. It basically takes a "Format" string which may contain placeholders with some extra formatting, and zero or more values to be inserted instead of those placeholders.
Your task is to implement the inverse function in your language of choice.
API
Method name should be either format1
or deformat
.
Input: 1st parameter will be the "Format" string, just like in the original format method. 2nd parameter will be the parsed string (see examples below). No other parameters are needed nor allowed.
Output: an array (or your language-of-choice's equivalent) of values that were extracted correspondingly with the placeholders in the format.
The placeholders are {0}
, {1}
, {2}
, etc.
In case of bad format you may throw an error, or return whatever you like.
In case of invalid input, you may throw an error, or return whatever you like. Invalid input is such that cannot be generated by String.Format using same format string, for example: '{0}{0}', 'AAB'
.
Examples
deformat('{0} {1}', 'hello world') => ['hello', 'world']
deformat('http{0}://', 'https://') => ['s']
deformat('http{0}://', 'http://') => [''] // array of one item which is an empty string
deformat('{0}{1}{0}', 'ABBA') => ['A', 'BB']
Ambiguity
In case of ambiguity you may return any suitable answer. For example:
deformat('{0} {1}', 'Edsger W. Dijkstra')
// both ['Edsger', 'W. Dijkstra'] and ['Edsger W.', 'Dijkstra'] are applicable.
Some More Rules
- To make it easier, there's no need to actually support formatting. You can forget all about leading zeros, decimal point or rounding issues. Just generate the values as strings.
- To make it non-trivial, Regular Expressions are not allowed.
- You don't need to take care of curly braces in input (i.e. 2nd input parameter will not contain any
{
s or}
s).
Winning
This is code-golf! (should be read as "This is Sparta!") the correct function having shortest length wins. Standard loopholes are forbidden.
deformat('{0}{1}{0}', 'ABBA') => ['A', 'BB']
, what if we were instead givendeformat('{0}{1}{0}', 'AAAA')
? \$\endgroup\$['', 'AAAA']
,['A', 'AA']
,['AA', '']
\$\endgroup\$deformat('{0}{1}{0}', 'ABBA') => ['', 'ABBA']
? If so, there's a cheap solution unless every string appears at least twice. \$\endgroup\$deformat('{0}_{1}_{0}', 'A_BB_A')
? \$\endgroup\$