【问题标题】:Missing template argument before [closed][关闭]之前缺少模板参数
【发布时间】:2018-10-11 16:22:19
【问题描述】:

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

//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;
}

//错误 在“当前”之前缺少模板参数

'end' 之前缺少模板参数

'current' 未在此范围内声明

是否有与我正在尝试做的不同的语法,因为我之前没有使用过正则表达式,并且是 c++ 的新手

【问题讨论】:

  • 发布完整代码,并将其与错误分开,并且您以某种方式遗漏了编译器会为您提供的行号等。
  • 即使使用string str1="hello \"trimthis\" please";,错误仍然存​​在。如果您打算获得几场比赛,您可以使用ideone.com/H5YXNt
  • regex_iterator 是一个类模板。您需要使用sregex_iterator。请查看en.cppreference.com/w/cpp/regex/regex_iterator 的示例代码。
  • @RSahu 在使用 sregex_iterator 后得到以下错误:无法将 'std::ostream {aka std::basic_ostream}' 左值绑定到 'std::basic_ostream&&'跨度>
  • @carlson.boy 查看我评论中的链接。您需要获得单个匹配项还是多个匹配项?

标签: c++ regex string


【解决方案1】:

问题 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;
}

【讨论】:

  • OP需要获取Group 1的值,所以你应该使用current-&gt;str(1)而不是current-&gt;str()
  • @WiktorStribiżew,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-12
  • 1970-01-01
  • 2016-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多