Boost logo

Boost :

From: John Maddock (john_at_[hidden])
Date: 2006-10-11 04:52:13


Aljaz wrote:
> Hello..
>
> Im working on my c++ application, and I have string (user input)
> where I would have to replace some variables/substrings in it..
> For example lets say user give input:
> string str "this is test $some_variable some more text $random(1-5)
> $random(1-9)";
>
> My program has a vector <string> of variables that program should
> look for, for this case lets say "some_variable" and "random".
> Now I want to replace $some_variable and both $random 'variables' with
> another string, and I want $some_variable to be replaced with some
> other string, and $random to be replaced with random number generated
> in range from 1-5 and 1-9, for instance $random(1-5) = "3", $random(1-9) =
> "6".
>
> So I would get "this is test some string some more text 3 6";
>
> This would be an easy thing to do, if I wouldnt have $random variable
> which makes different string each time you call it, so I'm in concern
> what would be a right/best approach to this.. I was thinking of using
> boost::regex and search with boost::regex
> expression("[%$](some_variable|random|some_more_variables)(<([^>]+)>)?");
> until I come to the string end..

I think this depends on how many variables you want to search for, the
"scalable" solution would probably be something like:

1) Search for the regex "\\$([-[:alnum:]_]+)"
2) Use sub-expression $1 in the matched regex to look up a *functor* in a
map<string, functor> and then call the functor - passing the matched string
as an argument if required - and use the return value as the replacement
string.

How does that sound?

HTH, John.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk