Bruno
Bruno

Reputation: 458

How to extract the unmatched portion of a string using a regex

I'm trying to display some messages to the user when the input is invalid.

I wrote this regex, to validade this pattern : (Name of 10 characters) (Number between 0-9)

e.g. Bruno 3

^([\w]{1,10})(\s[\d]{1})$

When the user input any invalid string, Is it possible to know what group is invalid and print a message? Something like that:

if (regex_match(user_input, e))
{
  cout << "input ok" << endl;
}
else
{
    if (group1 is invalid)
    {
        cout << "The name must have length less than 10 characters" << endl;
    }

    if (group2 is invalid)
    {
        cout << "The command must be between 0 - 9" << endl;
    }
}

Upvotes: 0

Views: 289

Answers (1)

Shakiba Moshiri
Shakiba Moshiri

Reputation: 23864

As I see you want to match 1 to 10 character then a single space and then a single digit but in 2 group

here is what you want:

^([a-zA-Z]{1,10})( \d)$

NOTE

\w is equivalent to [a-zA-Z0-9_]
So if you need only 10 characters you should use [a-zA-Z] not \w


C++ code

std::string string( "abcdABCDxy 9" );

std::basic_regex< char > regex( "^([a-zA-Z]{1,10})( \\d)$" );
std::match_results< std::string::const_iterator > m_result;

std::regex_match( string, m_result, regex );
std::cout << m_result[ 1 ] << '\n';   // group 1
std::cout << m_result[ 2 ] << '\n';   // group 2   

the output

1abcdABCDxy
 9

Upvotes: 1

Related Questions