Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex works on regex tester but not in c++

Tags:

c++

regex

quotes

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.

like image 940
Mike Drakoulelis Avatar asked Nov 02 '22 22:11

Mike Drakoulelis


1 Answers

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.

like image 101
user1676075 Avatar answered Nov 09 '22 22:11

user1676075