3

How can I get the name of the group corresponding to the pattern match using Boost regular expressions?

The following will output the matched expression to the given pattern. But how can I get the corresponding named group?

boost::regex pattern("(?<alpha>[0-9]*\\.?[0-9]+)|(?<beta>[a-zA-Z_]+)");

string s = "67.2 x  7 I am";

string::const_iterator start = s.begin();
string::const_iterator end   = s.end();
boost::sregex_token_iterator i(start, end, pattern);
boost::sregex_token_iterator j;

for ( ;i != j; ++i)
{
    cout << *i << endl;
        // '67.2' and '7' belongs to "alpha"
        // 'x', 'I', 'am' belongs to "beta"
}
Ralph
  • 31
  • 3

1 Answers1

2

You can get it from match_result It is for xpressive, but the same should work for Boost.Regex

Revolver_Ocelot
  • 8,609
  • 3
  • 30
  • 48
  • 1
    Why would you link to the documentation for a different library? – sehe Dec 20 '15 at 17:51
  • @sehe 1) I linked both. 2) I am not exactly sure what OP is using actually. – Revolver_Ocelot Dec 20 '15 at 18:19
  • 1
    2) `boost::regex` - I'm sure that's pretty conclusive – sehe Dec 20 '15 at 18:43
  • @sln Strange, documentation for Boost.regex I linked says "The overloads that accept a string, return a reference to the sub_match object representing the character sequence that matched the named sub-expression n. " – Revolver_Ocelot Dec 20 '15 at 22:39
  • 2
    @RevolverOcelot - Indeed, you are correct. I just tried this with `boost::regex` and `match["name"].str()` does work. I think a long time ago I was looking to get the _name_ given a group _number_ and visa/versa. Well, thanks. This is why I read the trivia at SO. Btw, any idea how the _named_ group could be used in `regex_replace()` on the replace side (and not via callback). I am only talking about the regular reggex, not expressive. Thank you! +1 –  Dec 22 '15 at 01:42