문제

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