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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <regex>
#include <map>
#include <iomanip>
std::vector<std::string> get_continents( const std::string& line )
{
static const std::regex words( "\\w+" ) ;
// http://en.cppreference.com/w/cpp/regex/regex_token_iterator
return { std::sregex_token_iterator( line.begin(), line.end(), words ), std::sregex_token_iterator{} } ;
}
int get_hub( const std::string& line )
{
static const std::regex hub( "^HUB(\\d+)\\-.*" ) ;
std::smatch match ;
// http://en.cppreference.com/w/cpp/regex/regex_search
if( std::regex_search( line, match, hub ) ) return std::stoi( match[1] ) ;
else return -1 ; // no match
}
std::pair< std::string, std::vector<int> > get_name_and_values( const std::string& line )
{
std::pair< std::string, std::vector<int> > name_and_values ;
// get the name
std::istringstream stm(line) ;
std::getline( stm, name_and_values.first, ',' ) ;
// get the values from the remainder of the line
const std::string residue = stm.str() ;
static const std::regex values( "\\d+" ) ;
const std::sregex_token_iterator end{} ;
for( std::sregex_token_iterator iter( residue.begin(), residue.end(), values ) ; iter != end ; ++iter )
name_and_values.second.push_back( std::stoi(*iter) ) ;
return name_and_values ;
}
int main()
{
std::cout << "continents: [ " ;
for( auto cont : get_continents( ",USA,EUROPE,ASIA" ) ) std::cout << std::quoted(cont) << ' ' ;
std::cout << "]\n" ;
std::cout << "hub: " << get_hub( "HUB23-12000,,," ) << '\n' ;
const auto name_and_values = get_name_and_values( "Transportation Cost,73,129,141" ) ;
std::cout << "name: '" << name_and_values.first << "' values: [ " ;
for( int v : name_and_values.second ) std::cout << v << ' ' ;
std::cout << "]\n" ;
}
|