Comment obtenir un remplacement de preg_match_all de base pour std :: string en C ++?
Question
avec "base", on entend: Seuls les opérateurs "+" (-> suivants ..) et "|" . (-> ou) sont nécessaires
Prototype:
preg_match_all(std::string pattern, std::string subject, std::vector<std::string> &matches)
Exemple d'utilisation:
std::vector<std::string> matches;
std::string pattern, subject;
subject = "Some text with a lots of foo foo and " + char(255) + " again " + char(255);
pattern = "/" + char(255) + char(255) + "+|foo+/";
preg_match_all(pattern, subject, matches);
Les matchs doivent être afterwardsa disponibles via matches[n]
. Quelqu'un a un indice sans avec boost et / ou PCRE? Sinon, comment je suis arrivé ce coup de pouce réalisé avec?
La solution
Vous pouvez Rollup quelque chose en utilisant std :: string :: find , faisant matchs par un foncteur, et en poussant les résultats sur un vecteur de chaîne.
La façon dont il est réalisé en coup de fouet est probablement exagéré pour ce que vous voulez -. Vous devez d'abord décomposer l'expression en lexèmes puis compiler une machine d'état pour l'analyse de la regexp donnée
Autres conseils
Ceci renvoie un vecteur de tous les matches d'un indice qu'ils ont été trouvés à.
std::vector<std::pair<std::string, unsigned int>> RegexPP::MatchAll(std::string pattern, std::string haystack) {
std::vector<std::pair<std::string, unsigned int>> matches;
std::regex p(pattern);
std::sregex_iterator start(haystack.begin(), haystack.end(), p), end;
for(; start != end; start++) {
auto match = *start; // dereference the iterator to get the match_result
matches.push_back(std::pair<std::string, unsigned int>(match.str(), match.position()));
}
return matches;
}
Regardez dans Boost.Regex, http : //www.boost.org/doc/libs/1_41_0/libs/regex/doc/html/index.html