2011-11-27 16 views
9

Come faccio a contare il numero di partite in C++ 11 di std::regex?numero Conte di partite

std::regex re("[^\\s]+"); 
std::cout << re.matches("Harry Botter - The robot who lived.").count() << std::endl; 

uscita prevista:

7

+2

E le stampe sono .... –

+0

@EdHeal ricevo un [errore di compilazione] (http://ideone.com/uxyrV): 'errore: 'regex_count' non è stato dichiarato in questo ambito'. ;) –

risposta

15

È possibile utilizzare regex_iterator per generare tutte le partite, quindi utilizzare distance di contarli:

std::regex const expression("[^\\s]+"); 
std::string const text("Harry Botter - The robot who lived."); 

std::ptrdiff_t const match_count(std::distance(
    std::sregex_iterator(text.begin(), text.end(), expression), 
    std::sregex_iterator())); 

std::cout << match_count << std::endl; 
+0

Puoi spiegare cosa restituisce 'std :: sregex_iterator' e quale 'distanza' tra i due mezzi? –

+1

@muntoo: 'sregex_iterator' è un typedef su' regex_iterator', che scorre su tutte le corrispondenze nel testo. 'distance' è la funzione di libreria standard che calcola il numero di elementi in un intervallo di iteratore (quindi, in questo caso, legge tutte le corrispondenze e restituisce quante ce ne sono). –

+0

Ciao. Anche se questo è un thread vecchio: penso che si possa abbandonare l'operazione match_count (che in C++ 11 non esiste comunque), come (w) sregex :: iterator già itera, come si dice, sulle partite. Quindi std :: distance dovrebbe restituire il conteggio della partita. L'ho provato usando gcc 4.6.1 e VS 2013 senza match_count e funziona perfettamente. – gilgamash

3

È possibile utilizzare questo:

int countMatchInRegex(std::string s, std::string re) 
{ 
    std::regex words_regex(re); 
    auto words_begin = std::sregex_iterator(
     s.begin(), s.end(), words_regex); 
    auto words_end = std::sregex_iterator(); 

    return std::distance(words_begin, words_end); 
} 
utilizzo 0

Esempio:

std::cout << countMatchInRegex("Harry Botter - The robot who lived.", "[^\\s]+"); 

uscita:

7 
Problemi correlati