Is there a way to interpolate a variable into a regex in C++11?

For example I want this regex: ^((?:\w+ ){$index})\w+
But I have to write all this code to get there:

vector< char > stringIndex( numeric_limits< int >::digits10 + 2 );
_itoa_s( index, stringIndex.begin()._Ptr, stringIndex.size(), 10 );
const string stringRegex( "^((?:\\w+ ){" );
regex goal( stringRegex + stringIndex.begin()._Ptr + "})\\w+" );

Surely there is a better way!

有帮助吗?

解决方案

Use std::to_string to convert the integer to string.

regex goal( "^((?:\\w+ ){" + std::to_string(index) + "})\\w+" );

By the way, the _Ptr member of vector<T>::iterator you keep accessing all over is implementation specific and makes your code unportable. You should use the vector::data member function instead.

Also, you can avoid all the additional backslashes by using raw string literals.

regex goal( R"reg(^((?:\w+ ){)reg" + std::to_string(index) + R"reg(})\w+)reg" );
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top