You can parse the pattern with regular expressions. A similar expression will match each field definition and separator:
Match m = Regex.Match(template, @"^(\[%(?<name>.+?)%\](?<separator>.)?)+$")
The mapping will contain two named groups for (name and separator), each of which will contain the number of captures for each time they match in the input string. In your example, the separation group will have less capture than the name group.
You can then iterate over the captures and use the results to extract the fields from the input string and save the values, for example:
if( m.Success ) { Group name = m.Groups["name"]; Group separator = m.Groups["separator"]; int index = 0; Dictionary<string, string> fields = new Dictionary<string, string>(); for( int x = 0; x < name.Captures.Count; ++x ) { int separatorIndex = input.Length; if( x < separator.Captures.Count ) separatorIndex = input.IndexOf(separator.Captures[x].Value, index); fields.Add(name.Captures[x].Value, input.Substring(index, separatorIndex - index)); index = separatorIndex + 1; }
Obviously, in a real program you will have to consider invalid input, etc., which I did not do here.
source share