为什么我不能在 C++11 中使用lookbehinds?前瞻工作正常。
std::regex e("(?<=a)b");
这将引发以下异常:
The expression contained mismatched ( and ).
这不会抛出任何异常:
std::regex e("a(?=b)");
我错过了什么?
C++11<regex>
使用 ECMAScript 的 (ECMA-262) 正则表达式语法,因此它不会有后视(C++11 支持的其他正则表达式也没有后视)。
如果您的用例需要使用后视,您可以考虑改用Boost.Regex。
正向后向 (?<=a)
匹配字符串中紧接在后向模式前面的位置。如果不期望重叠匹配,就像这里的情况一样,您可以简单地使用捕获组并仅提取组 1(如果您指定多个组值,则可以提取更多组值):
a(b)
这是一种使用以下方法提取所有匹配项的方法std::sregex_token_iterator
:
#include <iostream>
#include <vector>
#include <regex>
int main() {
std::regex rx("a(b)"); // A pattern with a capturing group
std::string sentence("abba abec"); // A test string
std::vector<std::string> names(std::sregex_token_iterator(
sentence.begin(), sentence.end(), rx, 1), // "1" makes it return Group 1 values
std::sregex_token_iterator()
);
for( auto & p : names ) std::cout << p << std::endl; // Print matches
return 0;
}
如果您只需要提取第一个匹配项使用regex_search
(不是regex_match
因为此函数需要完整的字符串匹配):
std::smatch sm;
if (regex_search(sentence, sm, rx)) {
std::cout << sm[1] << std::endl;
}
请参阅C++ 演示。