كيفية الحصول على استبدال preg_match_all أساسي لـ STD :: String in C ++؟
سؤال
مع "Basic" المقصود: فقط المشغلين "+" (-> التالية ..) و "|" (-> أو) مطلوبة.
النموذج المبدئي:
preg_match_all(std::string pattern, std::string subject, std::vector<std::string> &matches)
مثال الاستخدام:
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);
يجب أن تكون المباريات متاحة بعد ذلك عبر matches[n]
. شخص ما حصل على تلميح بدون استخدام تعزيز و/أو PCRE؟ إذا لم يكن كذلك ، كيف حصلت على هذا مع زيادة؟
المحلول
هل يمكن أن تدفع شيء ما باستخدام STD :: String :: Finding, ، يطابق القيام بمطابقات عبر functor ، ودفع النتائج إلى متجه السلسلة.
من المحتمل أن تكون الطريقة التي تتحقق بها في Boost مبالغة لما تريد - ستحتاج أولاً إلى تحلل التعبير إلى lexems ثم تجميع آلة الحالة لتحليل regexp المحدد.
نصائح أخرى
هذا سيعود متجهًا لجميع المباريات التي تم العثور عليها في الفهرس.
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;
}
انظر إلى Boost.regex ، http://www.boost.org/doc/libs/1_41_0/libs/regex/doc/html/index.html
لا تنتمي إلى StackOverflow