1

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?

1
  • Fast guess: You might have to escape the '\'. In your case: boost::regex rx("^\\[ (.+) \\]"); Commented Feb 13, 2014 at 14:15

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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"(^\[ (.+) \])");

2 Comments

Raw string literals are only available in C++11. And if he had C++11, he'd be using std::regex instead of Boost (presumably, at least).
@James Unless he's using gcc, std::regex doesn't really work in versions prior to 4.9.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.