Rene
Rene

Reputation: 2474

C++ 11 regex expression does not return groups as expected

I want to write a regulare expression that parses the syntax of a special format string. It should help me to detect format errors and also split the format string into the separate parts to handle.

But, as hard as I try, I cannot get the splitting to work as expected.

From what I've read in the documentation, the '(?: )' syntax should define a non-splitting group, whereas the normal bracket expression '( )' should define a sub-match that is returned separately. But it doesn't.

Here's my code:

#include <iostream>
#include <regex>
#include <string>

std::string parseCode( std::regex_constants::error_type etype);

int main()
{
   const std::string  regex_str( "(?:([^\\[]+)(\\[[^\\]]*\\])( +|\\n))");
   std::regex  atr;

   std::cout << "regex string = '" << regex_str << "'" << std::endl;

   try
   {
      atr.assign( regex_str);
   } catch (const std::regex_error& e)
   {
      std::cerr << "Error: " << e.what() << "; code: " << parseCode(e.code()) << std::endl;
      exit( EXIT_FAILURE);
   } // end try

   {
      const std::string  title( "First Title[]  Second Title[]   -Third Title[]");
      auto  regex_begin = std::sregex_iterator( title.begin(), title.end(), atr);

      for (std::sregex_iterator i = regex_begin; i != std::sregex_iterator(); ++i)
      {
         std::smatch  match = *i;
         std::cout << "got: '" << match.str() << "'" << std::endl;
      } // end for

      auto  subregex_begin = std::sregex_token_iterator( title.begin(),
         title.end(), atr, -1);

      for (std::sregex_token_iterator i = subregex_begin; i != std::sregex_token_iterator(); ++i)
      {
         std::cout << "got sub: '" << *i << "'" << std::endl;
      } // end for
   } // end scope

}

std::string parseCode( std::regex_constants::error_type etype)
{

   switch (etype)
   {
   case std::regex_constants::error_collate:
       return "error_collate: invalid collating element request";
   case std::regex_constants::error_ctype:
       return "error_ctype: invalid character class";
   case std::regex_constants::error_escape:
       return "error_escape: invalid escape character or trailing escape";
   case std::regex_constants::error_backref:
       return "error_backref: invalid back reference";
   case std::regex_constants::error_brack:
       return "error_brack: mismatched bracket([ or ])";
   case std::regex_constants::error_paren:
       return "error_paren: mismatched parentheses(( or ))";
   case std::regex_constants::error_brace:
       return "error_brace: mismatched brace({ or })";
   case std::regex_constants::error_badbrace:
       return "error_badbrace: invalid range inside a { }";
   case std::regex_constants::error_range:
       return "erro_range: invalid character range(e.g., [z-a])";
   case std::regex_constants::error_space:
       return "error_space: insufficient memory to handle this regular expression";
   case std::regex_constants::error_badrepeat:
       return "error_badrepeat: a repetition character (*, ?, +, or {) was not preceded by a valid regular expression";
   case std::regex_constants::error_complexity:
       return "error_complexity: the requested match is too complex";
   case std::regex_constants::error_stack:
       return "error_stack: insufficient memory to evaluate a match";
   default:
       return "";
   }
}

And here's the output:

regex string = '(?:([^\[]+)(\[[^\]]*\])( +))'
got: 'First Title[]  '
got: 'Second Title[]   '
got sub: ''
got sub: ''
got sub: '-Third Title[]'

And this is what I want/expect:

regex string = '(?:([^\[]+)(\[[^\]]*\])( +))'
got: 'First Title[]  '
got: 'Second Title[]   '
got: '-Third Title[]'
got sub: 'First  Title'
got sub: '[]'
got sub: '  '
got sub: 'Second  Title'
got sub: '[]'
got sub: '  '
got sub: '-Third Title'
got sub: '[]'

I am using g++ 5.3.1 on RHEL 7.2.
Got the same result with g++ 6.3 on IdeOne.com: https://ideone.com/dj4Mqf

What am I doing wrong?

Upvotes: 2

Views: 209

Answers (1)

rustyx
rustyx

Reputation: 85341

1) Your regex doesn't match the last part, change it to:

  const std::string  regex_str("([^\\[]+)(\\[[^\\]]*\\])(\\s+|\\n|$)");

2) match.str() returns the whole matched string, to extract matched groups, use operator[]:

  std::smatch  match = *i;
  std::cout << "got: 1='" << match[1] << "' 2='" << match[2] << "' 3='" << match[3] << "'" << std::endl;

Output:

regex string = '([^\[]+)(\[[^\]]*\])(\s+|\n|$)'
got: 1='First Title' 2='[]' 3='  '
got: 1='Second Title' 2='[]' 3='   '
got: 1='-Third Title' 2='[]' 3=''

Upvotes: 3

Related Questions