Palace Chan
Palace Chan

Reputation: 9213

boost regex not matching?

I am trying to follow the example here:

http://www.boost.org/doc/libs/1_31_0/libs/regex/doc/syntax.html

I want to match lines of this form:

[ foo77 ]

which should be simple enough, I tried a code snippet like this:

boost::regex rx("^\[ (.+) \]");

boost::cmatch what;
if (boost::regex_match(line.c_str(), what, rx)) std::cout << line << std::endl;

but I am not matching those lines. I tried the following variant expressions:

"^\[[:space:]+(.+)[:space:]+\]$" //matches nothing
"^\[[:space:]+(.+)[:space:]+\]$" //matches other lines but not the ones I want.

what am I doing wrong?

Upvotes: 1

Views: 1235

Answers (2)

jfly
jfly

Reputation: 8010

change boost::regex rx("^\[ (.+) \]"); to boost::regex rx("^\\[ (.+) \\]");, it will work fine, the compiler should warn about the unrecognized character escape sequence.

Upvotes: 1

Praetorian
Praetorian

Reputation: 109269

You need to escape the \ within the regular expression, otherwise your compiler will consider "\[" as an (invalid) escape sequence.

boost::regex rx("^\\[ (.+) \\]");

A better solution is to use raw string literals.

boost::regex rx(R"(^\[ (.+) \])");

Upvotes: 0

Related Questions