Mike Drakoulelis
Mike Drakoulelis

Reputation: 789

regex works on regex tester but not in c++

I am trying to get the content between quotes from a file, and I am using regex. This is the regex I am using:

id=\"([^\"]+)\"|title=\"([^\"]+)\"

As you can see, every special character is escaped. It works perfectly in regex tester, but when used in c++ code the title isn't found. ID is always found just fine. I have tried several variations, and even removed half of it (before |)

id="60973129" title="EPA"

This is the C++ code that I am using:

std::regex rgx("id=\"([^\"]+)\"|title=\"([^\"]+)\"");
std::smatch match;

if (std::regex_search(line, match, rgx)) {
    for (int i=0; i < match.size(); ++i) {
            std::cout << match[i];
    }
}

EDIT: I found that if put separately, the title=\"(.+?)\" does work, but then I have to use several regexes, which defeats my purpose, since I will need to scan longer lines later.

Upvotes: 5

Views: 10452

Answers (1)

user1676075
user1676075

Reputation: 3086

It probably works in a tester because it's saying "does anything match" within the string, as opposed to "does the entire thing match".

Anyway, | is an "or", find one or the other. To match the string as shown, change | to either a space, or an indicator for any amount of whitespace, such as [ \t]+ and I suspect it will work fine then.

Upvotes: 2

Related Questions