为什么注释的正则表达式与未注释的正则表达式的行为不同?我认为 '^' 也标志着行的开始。不是吗?
#include <iostream>
#include <regex>
int main()
{
std::string str ("this subject has a submarine as a subsequence");
std::regex re ("\\b(sub)([^ ]*)");
// std::regex re ("^(sub)([^ ]*)");
// std::regex re ("(^sub)([^ ]*)");
std::cout << "entire matches:";
std::regex_token_iterator<std::string::iterator> rend;
std::regex_token_iterator<std::string::iterator> a ( str.begin(), str.end(), re );
while (a!=rend) std::cout << " [" << *a++ << "]";
std::cout << std::endl;
return 0;
}
它工作得很好。它无法匹配任何内容,因为您的行不是以字母“sub”开头,而是以字母“The”开头
解释这些正则表达式:
\\b(sub)([^ ]*)
新单词的开头,以 sub 开头,后跟一定数量的非空格字符。两个捕获组,一个用于“子”,另一个用于其他字符。
^(sub)([^ ]*)
新行的开始,以 sub 开头,后跟一定数量的非空格字符。两个捕获组,一个用于“子”,另一个用于其他字符。
(^sub)([^ ]*)
[编辑:已修复,谢谢约翰] 同上,但锚点是捕获组的一部分。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句