מתן ויס
מתן ויס

Reputation: 1

Why this regular expression isn't matching this string?

I have the next code sample:

#include <regex>
#include <iostream>
using namespace std;

int main()
{
    string input;
    regex third("([a-zA-Z]*) ([a-zA-Z]*)[\s]*([a-zA-Z]*)");
    smatch third_match;
    getline(cin, input);
    while (input != "q")
    {
        if(regex_match(input, third_match, third))
            cout << "Ok" << endl;
        getline(cin, input);
    }
    return 0;
}

If I enter a string, say:

"I am_____________happy" (alot of spaces instead of the underscore ('_').

Then it should work- because I have a "word" and then a "space" and then a "word" and then "how many spaces that I want, and then a "word", and this should match my expression above, but is doesnt. Why?

Upvotes: 0

Views: 40

Answers (2)

Shakiba Moshiri
Shakiba Moshiri

Reputation: 23894

because you used regex_match and instead you should use regex_search
match will be true if the entire mach exactly find serach will be true if at least one match find
Also all escape characters should be \\

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477464

You need to escape the backslash:

regex third("([a-zA-Z]*) ([a-zA-Z]*)[\\s]*([a-zA-Z]*)");
//                                  ^^^^^

Upvotes: 1

Related Questions