views:

247

answers:

1

Specifically, I have an array of strings called val, and want to replace all instances of "%{n}%" in the input with val[n]. More generally, I want the replace value to be a function of the match value. This is in C++, so I went with Boost, but if another common regex library matches my needs better let me know.

I found some .NET (C#, VB.NET) solutions, but I don't know if I can use the same approach here (or, if I can, how to do so).

I know there is this ugly solution: have an expression of the form "(%{0}%)|(%{1}%)..." and then have a replace pattern like "(1?" + val[0] + ")(2?" + val[1] ... + ")".

But I'd like to know if what I'm trying to do can be done more elegantly.

Thanks!

+1  A: 

I don't beleive boost::regex has an easy way to do this. The most straightfoward way that I can think of would be to do a regex_search using the "(%{[0-9]+}%)" pattern and then iterate over the sub-matches in the returned match_results object. You'll need to build a new string by concatenating the text from between each match (the match_results::position method will be your friend here) with the result of converting sub-matches to the values from your val array.

Brett Hall
Thanks, I had a feeling this would be the answer, but wanted to double check. Will mark as answer if no one else chimes in to the contrary.
endtime
I'm not an expert on boost::regex, I've only used it for somewhat simple things, so take my answer with a grain of salt. That being said, I couldn't find anything in the docs for the library that make what you want to do easy. Some expert, if there are any, might chime in to the contrary. You might want to look at boost::spirit for what you are doing since you can attach "semantic actions" to parts of a match to a parse tree -- you're array look-up would fit in well as a semantic action. I find spirit much easier to use than regex for anything at all complicated.
Brett Hall
Thanks, that's great to know about, but I think in this case it's probably overkill versus just using my ugly string-construction solution.
endtime