使用C++正则提取字符串中子串时遇模板参数缺失错误求助
Hey there, let's sort out those missing template arguments errors you're hitting with your regex code! The problem comes down to how regex_iterator works in C++—it's a template class, so you have to tell the compiler exactly what type of iterator it's dealing with.
错误原因分析
Your code declares regex_iterator current and regex_iterator end without specifying template arguments. The compiler has no way to know what kind of character/iterator you're using here, hence the errors:
missing template arguments before 'current'
missing template arguments before 'end'
修正后的代码(两种方式)
方式1:显式指定模板参数
#include <regex> #include <iostream> using namespace std; int main(){ string str1="hello \"trimthis\" please"; regex rgx("\"([^\"]*)\""); // 捕获被引号包裹的内容 // 显式指定模板参数为string::iterator regex_iterator<string::iterator> current(str1.begin(), str1.end(), rgx); regex_iterator<string::iterator> end; while (current != end) { // [1] 表示取第一个捕获组的内容(去掉引号的部分) cout << (*current)[1] << endl; current++; } return 0; }
方式2:用auto自动推导类型(C++11及以上)
如果你的编译器支持C++11或更高版本,用auto会更简洁,编译器会自动推导regex_iterator的模板参数:
#include <regex> #include <iostream> using namespace std; int main(){ string str1="hello \"trimthis\" please"; regex rgx("\"([^\"]*)\""); auto current = sregex_iterator(str1.begin(), str1.end(), rgx); auto end = sregex_iterator(); while (current != end) { cout << (*current)[1] << endl; current++; } return 0; }
注意:这里用sregex_iterator是regex_iterator<string::iterator>的别名,专门用于std::string的迭代器,写起来更方便。
额外提示
- 直接输出
*current会打印整个匹配结果(包括前后的引号),如果你只想获取引号里的内容,记得用(*current)[1]来访问第一个捕获组。 - 确保你的编译器启用了C11或更高版本(比如编译时加
-std=c++11参数),因为regex库和auto都是C11引入的特性。
内容的提问来源于stack exchange,提问作者carlson.boy

