parsing - Evaluate a Special Expression in C# -


i have string have special substrings in special format:

$( variablename )

and pattern can repeat nested many times:

$( variablename $( anothervariablename ) )

such as: [ test string ]

here test string contain $(variablea) , $(variableb$(variablec))

for test string let assume that

$(variablea) = a, $(variableb) = b, $(variablec) = c, $(variablebc) = y

what want replace special patters -> $(variablename) actual values such resulting string should be:

here test string contain , y

any suggestion generic , elegant solution?

here straightforward solution performing recursive descent parsing:

public static string replace(     string input ,   ref int pos ,   idictionary<string,string> vars ,   bool stoponclose = false ) {     var res = new stringbuilder();     while (pos != input.length) {         switch (input[pos]) {             case '\\':                 pos++;                 if (pos != input.length) {                     res.append(input[pos++]);                 }                 break;             case ')':                 if (stoponclose) {                     return res.tostring();                 }                 res.append(')');                 pos++;                 break;             case '$':                 pos++;                 if (pos != input.length && input[pos] == '(') {                     pos++;                     var name = replace(input, ref pos, vars, true);                     string replacement;                     if (vars.trygetvalue(name, out replacement)) {                         res.append(replacement);                     } else {                         res.append("<unknown:");                         res.append(name);                         res.append(">");                     }                     pos++;                 } else {                     res.append('$');                 }                 break;             default:                 res.append(input[pos++]);                 break;         }     }     return res.tostring(); } public static void main() {     const string input = "here test string contain $(variablea) , $(variableb$(variablec))";     var vars = new dictionary<string, string> {         {"variablea", "a"}, {"variableb", "b"}, {"variablec", "c"}, {"variablebc", "y"}     };     int pos = 0;     console.writeline(replace(input, ref pos, vars)); } 

this solution reuses implementation of replace built name of variable replace calling stoponclose flag set true. top-level invocation not stop on reaching ')' symbol, letting use unescaped.

here demo on ideone.


Comments

Popular posts from this blog

design - Custom Styling Qt Quick Controls -

Unable to remove the www from url on https using .htaccess -