Is there a way to interpolate a variable into a regex in C++11?
有没有办法在C ++ 11中将变量插入到正则表达式中?
For example I want this regex: ^((?:\w+ ){$index})\w+
But I have to write all this code to get there:
例如,我想要这个正则表达式:^((?:\ w +){$ index})\ w +但是我必须编写所有这些代码来实现:
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!
当然有更好的方法!
1 个解决方案
#1
4
Use std::to_string
to convert the integer to string.
使用std :: 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.
顺便说一下,你继续访问的vector
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" );
#1
4
Use std::to_string
to convert the integer to string.
使用std :: 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.
顺便说一下,你继续访问的vector
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" );