vendredi 1 avril 2016

std::regex search and replace

I need a hand on getting the regex expression to work correctly with the following source string:

<path d="M 1434.9,982.0 L 1461.3,982.0  L 1461.3,1020.5  L 1434.9,1020.5 z " stroke-width="1" stroke="#008000" fill="none"/>

On such line, I need to adjust the stroke-width and stroke values without impacting the rest of the content.

So far, I'm doing this in 2 steps, first replacing the stroke value and then replacing the stroke-width value, this is where I get strange results, see below.

Snippet:

string s("<path d=\"M 1434.9,982.0 L 1461.3,982.0  L 1461.3,1020.5  L 1434.9,1020.5 z \" stroke-width=\"1\" stroke=\"#008000\" fill=\"none\"/>");                   
std::regex re("stroke=\".+\" ");
cout << "0. " << s << endl;
s = std::regex_replace(s, re, "stroke=\"#00FF00\" ");
cout << "1. " << s << endl;
re = "stroke-width=\".+\" .*?";
s = std::regex_replace(s, re, "stroke-width=\"3\" ");
cout << "2. " << s << endl;

Output:

0.     <path d="M 1434.9,982.0 L 1461.3,982.0  L 1461.3,1020.5  L 1434.9,1020.5 z " stroke-width="1" stroke="#008000" fill="none"/>
1.     <path d="M 1434.9,982.0 L 1461.3,982.0  L 1461.3,1020.5  L 1434.9,1020.5 z " stroke-width="1" stroke="#00FF00" fill="none"/>
2.     <path d="M 1434.9,982.0 L 1461.3,982.0  L 1461.3,1020.5  L 1434.9,1020.5 z " stroke-width="3" fill="none"/>

It's almost what I'm looking for except that in the 2. string output, the stroke field is gone!

I'm currently using the std::regex, but I'm open to boost::regex too. Appreciate any pointers on this.

Aucun commentaire:

Enregistrer un commentaire