// Example 1 #include #include #include int main() { std::string input; // regex integer("(\\+|-)?[[:digit:]]+"); std::regex integer("(\\+|-)?([[:digit:]]+)"); std::smatch match; // As long as the input is correct ask for another number while (true) { std::cout << "Give me an integer! (q to quit)" << std::endl; std::getline(std::cin, input); // cin >> input; if (!std::cin) break; // Exit when the user inputs q if (input == "q") break; // Apparently, hitting enter, doesn't give you a blank input! use getline. std::cout << "Length: " << input.length() << " Empty? " << input.empty() << std::endl; if (input.empty()) break; // I need position and length. std::vector> pos_len; for (auto it = std::sregex_iterator(input.begin(), input.end(), integer); it != std::sregex_iterator(); ++it) { pos_len.push_back(std::make_pair(it->position(), it->length() ) ); std::cout << it->position() << " " << it->length() << " : " << it->str() << std::endl; } for (std::vector>::iterator vit = pos_len.begin(); vit != pos_len.end(); ++vit ) { std::pair p; p = *vit; cout << (*vit).first << "," << (*vit).second << endl; cout << p.first << "," << p.second << endl; } #ifdef RX1 if (std::regex_match(input, match, integer)) { std::cout << "integer" << std::endl; for (int i = 0; i < match.size(); ++i) { std::cout << "match " << i << " (" << match[i] << ") At " << match.position(i) << " of " << match.length(i) << " chars." << std::endl; } for (std::smatch::iterator im = match.begin(); im != match.end(); ++im) { std::cout << "matches:" << *im << std::endl; } } else { std::cout << "Invalid input" << std::endl; } int offset = 0; while (std::regex_search(input, match, integer)) { std::cout << "input: [" << input << "]" << std::endl; std::cout << offset << " match len " << match.length(0) << std::endl; for (int i = 0; i < match.size(); ++i) { std::cout << "match " << i << " (" << match[i] << ") At " << offset + match.position(i) << " of " << match.length(i) << " chars." << std::endl; } for (auto x : match) { std::cout << x << " "; } std::cout << std::endl; input = match.suffix().str(); offset += match.length(0) + match.prefix(0).size(); } #endif } }