Sono nuovo alle espressioni regolari C++ e non posso farle funzionare con le stringhe invece di char *. Gli esempi che ho visto fino ad ora erano sempre per le stringhe.Perché un codice di espressione regolare C++ che funziona con "cmatch" genera un'eccezione con "smatch"?
Il mio vero programma, che non cercherò nemmeno di mostrare qui, utilizza le corrispondenze secondarie ma non sono riuscito a farle funzionare, quindi ho provato a modificare un esempio di funzionamento molto semplice ma non funziona neanche. Io uso Visual Studio 2010 Ultimate.
L'originale - lavoro - Codice:
const char *first = "abcd";
const char *last = first + strlen(first);
std::cmatch mr;
std::regex rx("abc");
std::regex_constants::match_flag_type fl = std::regex_constants::match_default;
std::cout << "search(f, l, \"abc\") == " << std::boolalpha
<< regex_search(first, last, mr, rx) << std::endl;
std::cout << " matched: \"" << mr.str() << "\"" << std::endl;
std::cout << "search(\"xabcd\", \"abc\") == " << std::boolalpha
<< regex_search("xabcd", mr, rx) << std::endl;
std::cout << " matched: \"" << mr.str() << "\"" << std::endl;
Il codice modificato:
const string first = "abcd"; // char * => string
std::smatch mr; // cmatch => smatch
std::regex rx(string("abc"));
std::regex_constants::match_flag_type fl = std::regex_constants::match_default;
// this works:
std::cout << "search(f, l, \"abc\") == " << std::boolalpha
<< regex_search(first, mr, rx) << std::endl;
std::cout << " matched: \"" << mr.str() << "\"" << std::endl;
// after the next line executes mr seems good to me:
// mr[0] = {3, matched:true, first="abcd", second="d",...}
std::cout << "search(\"xabcd\", \"abc\") == " << std::boolalpha
<< regex_search(string("xabcd"), mr, rx) << std::endl;
// but the following line gives the error
// "Debug assertion failed"
// Expression: string iterators incompatible
std::cout << " matched: \"" << mr.str() << "\"" << std::endl;
Strano che una parte del codice modificato funziona, mentre la parte successiva causa un'eccezione. Ho anche provato a usare mr [0] .str() ma ho ricevuto lo stesso messaggio di errore. Potresti aiutarmi a risolvere questo problema?
Grazie! Vedo che non ci ho pensato. Questo spiega anche completamente perché il mio codice originale si blocca. – afalco