之前缺少模板参数

Missing template argument before

本文关键字:参数      更新时间:2023-10-16

我正在尝试使用正则表达式获取包含在字符串中的子字符串,但似乎收到以下错误:

//code
#include <regex>
#include <iostream>
using namespace std;
int main(){
string str1="hello "trimthis" please";
regex rgx(""([^"]*)""); // will capture "trimthis"
regex_iterator current(str1.begin(), str1.end(), rgx);
regex_iterator end;
while (current != end)
cout << *current++; 
return 0;
}

//错误 "当前"之前缺少模板参数

"结束"之前缺少模板参数

在此范围内未声明"当前">

是否有与我尝试执行的操作不同的语法,因为我以前没有使用过正则表达式并且是 c++ 的新手

问题 1

regex_iterator是一个类模板。您需要使用sregex_iterator.

问题2

*current计算结果为std::smatch。将此类对象插入std::ostream没有重载。您需要使用:

cout << current->str();

这是对我有用的程序的更新版本。

//code
#include <regex>
#include <iostream>
using namespace std;
int main(){
string str1="hello "trimthis" please";
regex rgx(""([^"]*)""); // will capture "trimthis"
sregex_iterator current(str1.begin(), str1.end(), rgx);
sregex_iterator end;
while (current != end)
{
cout << current->str() << endl;  // Prints the entire match "trimthis"
cout << current->str(1) << endl; // Prints the group, trimthis
current++; 
}
return 0;
}