Regexp新手的东西

时间:2014-10-28 22:23:38

标签: c++ regex visual-c++

我想从"[self hello];""self""hello"进行标记化......我做错了什么? (MSVC ++)

#include <iostream>
#include <regex>
#include <string>

using namespace std;

int main() {
    string s = "[self hello];";
    string x1 = R"raw(\[(\w+)\s+(\w+)\]\;)raw";
    regex re(x1);

    sregex_token_iterator it(s.begin(),s.end(),re,-1);
    sregex_token_iterator reg_end;
    for (; it != reg_end; ++it)
    {
        auto a = *it;
        std::cout << a; // doesn't work. Displays empty string.
     }
}

1 个答案:

答案 0 :(得分:2)

您已为iterator constructor指定了特殊值-1。这意味着它应该给出无与伦比的部分。但是,您的整个字符串是匹配的。如果只进行字符串匹配(live example)的一部分,则可以看到这有效:

string s = "abc[self hello];def";

输出:

  

ABC
  DEF

或者,您可以在匹配项之间添加文字(live example):

string s = "abc[self hello];def[beep boop];ghi";

输出:

  

ABC
  高清
  GHI

以下是使用与第一个示例相同的字符串的其他一对值和输出:

  

0或遗漏:[self hello];
  1:自我   2:你好

相关问题