regex_search

Why does inputting "integral123" result in the last character of the first group being displayed, while the second group displays the first number?

1
2
3
4
5
6
7
8
9
10
    regex expr("([[:alpha:]])([[:digit:]])");
    smatch sm;
    bool matched{};
    for(string str{}; cin >> str; ) {
        cout << ( (matched = regex_search(str, sm, expr)) ? "Match!" : "No match!" ) << "\n";
        if(matched)
            cout << "User: " << sm[1] << "\t" "Number: " << sm[2] << "\n\n";
        else
            cout << "\n";
    }


integral123
User: l Number: 1
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <regex>
#include <iomanip>

int main()
{
    // (one or more alpha characters) immediately followed by (one or more digits)
    const std::regex expr( "([[:alpha:]]+)([[:digit:]]+)" ) ;

    const std::string str = "integral123" ;

    std::smatch mr ;
    if( std::regex_match( str, mr, expr ) ) // regex_match to match an entire string
    {
        std::cout << "user: " << std::quoted( mr[1].str() ) << "  number: " << mr[2] << '\n' ;
    }
    else std::cerr << "not matched\n" ;
 }

http://coliru.stacked-crooked.com/a/8313923f1722fef2
Topic archived. No new replies allowed.