Search code examples
c++regexboostboost-regex

Why regex_match do not match my regex?


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.


Solution

  • 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.