creating strings with specific conditions.

I'm trying to create a Book class with a string member representing the ISBN. The ISBN must follow the format n-n-n-x where each n is an integer and x is a character or digit. I'm having quite a bit of difficulty doing this elegantly, can anyone help me out? Thanks in advance.
Use the standard regular expressions library. http://en.cppreference.com/w/cpp/regex

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
#include <regex>
#include <iomanip>

// length is 13, format is n-n-n-x where each n is an integer and x is either x or X
bool valid_isbn10( std::string str )
{
    // [0-9]        digit (decimal)
    // [0-9]+       one or more digits
    // [0-9]+-      one or more digits, followed by a hyphen
    // ([0-9]+-){3} (one or more digits, followed by a hyphen) repeated thrice
    // [0-9xX]      digit or x or X
    // details: http://en.cppreference.com/w/cpp/regex/ecmascript
    static const std::regex pattern( "([0-9]+-){3}[0-9xX]" ) ;

    // http://en.cppreference.com/w/cpp/regex/regex_match
    return str.size() == 13 && std::regex_match( str, pattern ) ;
}

int main()
{
    for( std::string str : { "12-0-2345-X", "12-0-234567-X", "12-023456-7-5",  "12-0-23-456-X", "12000-23456-X", "12-0-234x67-X" } )
        std::cout << std::quoted(str) << " valid? " << std::boolalpha << valid_isbn10(str) << "\n\n" ;
}

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