regex for nested mark-up/functions -
i creating program offer few functions can entered user. let's have function convert string upper-case function $upper(string)
, function $lower(string)
. user can enter in text box while using placeholders insert content (e.g. %t title of song). using both placeholders , functions, user can enter complete naming pattern.
functions can nested , want execute inner-most function first. looking regex identify it. in english, looking a function (and value) not contain function.
during tests, use hyphens instead of brackets , no $-sign. lot easier read. functions during testing lower-sometext-
.
this guess far:
(lower|upper)-(?!((lower|upper)-.*-))-
i read follows:
- find word
upper
orlower
, - followed hyphen,
- followed not word
upper
orlower
, hyphen, random number of random characters , hyphen - followed hypen.
but won't accept lower-sometext-
. trying different things more 2 hours can't figure out...
use different approach: instead of looking inner-most function first, start outermost function - , resolve value recursively.
so string upper(lower(sometext))
first "handle" upper. before apply toupper() call same function on value - in case lower(sometext)
. same thing again: apply tolower() result of execute function value - in case sometext
. since not contain function, execute method return sometext
, end recursion.
i have created function in c#
public string execute(string text) { string pattern = @"(lower|upper)\((.*)\)"; match m = regex.match(text, pattern); if (m.success) { switch (m.groups[1].value) { case "lower": return execute(m.groups[2].value).tolower(); case "upper": return execute(m.groups[2].value).toupper(); default: return null; } } else return text; }
and can call function string:
string result = "upper(lower(sometext))";
again: important part inside switch: before call tolower()
or toupper()
call execute method value. result of function literal , never contain function. also, scales well.
Comments
Post a Comment