1

My regular expression with a '}' is throwing exception when I use the microsoft tr1::regex. But the same regex work fine with other regular expression interpreters.

Here is the simplified sample code.

string source = "{james}";
string exp = "{(.*)}";
std::tr1::cmatch res;
std::tr1::regex rx(exp);// Throws Exception here
while(std::tr1::regex_search(source.c_str(), res, rx))
{
    std::cout <<" "<< res[1]<<endl<<"....."<<endl;  
    source = res.suffix().str();
}

The same code works fine here. What am I missing here? I have tried escaping the '{', but that also doesn't work

string source = "\{james\}";
string exp = "\{(.*)\}";

I am using Visual studio 2010.

Thanks Sunil

S_R
  • 493
  • 1
  • 9
  • 22
  • Should be `string_exp = "\{(.*)\}"`. There are also cases where you might have to escape the back-slash as well depending on your `std::regex` constructor flags. Also note that you can't have `string exp = string exp =...` You cannot have spaces in variable names. – Brandon Feb 19 '14 at 19:09
  • Different regexp engines have different behaviour, feature set and sometimes even some different symbols like the {} in the case of tr1. You always have to check when you switch between engines, there is no general standard. Pearl is a quasi standard, but it only brings some consitancy, its no rule for engine developers. Always read the docs of a new engine you work with. – Marcel Blanck Feb 19 '14 at 19:21

2 Answers2

0

{} are RegEx metacharacters. They must be escaped.

tenub
  • 3,386
  • 1
  • 16
  • 25
0

In that regex, you need backslashes to escape those braces:

\{ \}

The regex container is a string, so the backslashes need to be part of that string. To have backslashes in a string, which is written in source code, you need to escape them with... backslashes:

"\\" followed by "{"

So, try this:

string exp = "\\{(.*)\\}";

If you would have to feed that string through an additional parser, which also escapes with backslashes, then you gonna have to double the nuber of backslashes again.

You will need "\\\\" to match a backslash.

comonad
  • 5,134
  • 2
  • 33
  • 31