为什么我不能在C++11中使用lookbehinds?Lookahead可以正常工作。
std::regex e("(?<=a)b");
这将抛出以下异常:
The expression contained mismatched ( and ).
这段代码不会抛出任何异常:
std::regex e("a(?=b)");
我错过了什么?
为什么我不能在C++11中使用lookbehinds?Lookahead可以正常工作。
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)
匹配字符串中紧接在后顾断言模式之前的位置。如果不希望出现重叠匹配,就像这里的情况一样,您可以简单地使用一个捕获组并仅提取第一组(甚至更多的组值,如果您指定了多个)。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;
}