Michael Chourdakis
Michael Chourdakis

Reputation: 11148

Regexp newbie stuff

I want to tokenize from "[self hello];" to "self" and "hello" ... what am I doing wrong ? (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.
     }
}

Upvotes: 0

Views: 44

Answers (1)

Qaz
Qaz

Reputation: 61900

You've given the special value -1 to the iterator constructor. This means it should give the unmatched sections. However, your whole string is matched. You can see this have an effect if you make only part of the string match (live example):

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

Output:

abc
def

Or, you can add text between matches (live example):

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

Output:

abc
def
ghi

Here are some other pairs of values and outputs using the same string as the first example:

0 or left out: [self hello];
1: self
2: hello

Upvotes: 2

Related Questions