1

I have to write a C++ regex but i am not able to get correct result on regex_match as i am new to c++. The string for testing is: D10A7; Lets say unsigned_char[] stringToBeTested="D10A7"; What i have to do is after regex_match i will extract 10 and 7 in two different short variabled for application's use. Digit after 'D' will always be two digit and digit after 'A' is always be one digit. My try to do it is:

boost::regex re("D([0-9])(/([0-9]))?");
boost::cmatch mr;
if ( boost::regex_match(stringToBeTested, mr, re ) )
{       
    number = atoi(mr.str(1).c_str()); //Must be 10
    axis = atoi(mr.str(2).c_str()); //Must be 7
}

How to generate the boost::regex re for this condition, Please explain the answer in detail.

  • 1
    What's with the slash? There's no slash in the string you try to match? – Some programmer dude Mar 29 '17 at 10:31
  • On a side note I recommend to use the more C++ish [`std::stoi()`](http://en.cppreference.com/w/cpp/string/basic_string/stol) which allows you to get rid of the `.c_str()` which should have no use in pure C++ code, e. g. `number = stoi(mr.str(1))`. – zett42 Mar 29 '17 at 10:42

1 Answers1

3

The regex_match requires a full string match. You need to provide a pattern that will do that.

boost::regex re("D([0-9]{2})A([0-9])");

Here,

  • D - matches D
  • ([0-9]{2}) - captures into Group 1 two digits
  • A - matches A
  • ([0-9]) - captures into Group 2 a single digit.

See the online demo of the above regex.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • thanks for the answer , Just to clear a doubt, Lets say i have 'D124' and it has to store number =12 and axis=3 .What will be the regix now (Because i have removed 'A' here). And what is the role of '/' in the regex. I am not able to find good documentation yet to understand well. – tosttest tosttest Mar 29 '17 at 11:09
  • 1
    You may use [`^D([0-9]{2})(?:A?([0-9]))?$`](https://regex101.com/r/Zp1vk0/1) then. The `/` symbol has no specific meaning in a regex, it is matched as a literal `/` symbol. – Wiktor Stribiżew Mar 29 '17 at 11:52
  • 1
    The `(?:...)` construct is a *non-capturing group* that only groups subpatterns, so as to quantify them or use alternatives. It does not create a submatch. A `?` after `A` is a *greedy quantifier* that matches 1 or 0 occurrences of the pattern it modifies. – Wiktor Stribiżew Mar 29 '17 at 12:19