开发者

C++, Boost regex, replace value function of matched value?

开发者 https://www.devze.com 2022-12-11 03:23 出处:网络
Specifically, 开发者_JS百科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 t

Specifically, 开发者_JS百科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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消