input-int.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Example 1
  2. #include <iostream>
  3. #include <regex>
  4. #include <string>
  5. int main() {
  6. std::string input;
  7. // regex integer("(\\+|-)?[[:digit:]]+");
  8. std::regex integer("(\\+|-)?([[:digit:]]+)");
  9. std::smatch match;
  10. // As long as the input is correct ask for another number
  11. while (true) {
  12. std::cout << "Give me an integer! (q to quit)" << std::endl;
  13. std::getline(std::cin, input);
  14. // cin >> input;
  15. if (!std::cin)
  16. break;
  17. // Exit when the user inputs q
  18. if (input == "q")
  19. break;
  20. // Apparently, hitting enter, doesn't give you a blank input! use getline.
  21. std::cout << "Length: " << input.length() << " Empty? " << input.empty() << std::endl;
  22. if (input.empty())
  23. break;
  24. // I need position and length.
  25. std::vector<std::pair<int,int>> pos_len;
  26. for (auto it = std::sregex_iterator(input.begin(), input.end(), integer);
  27. it != std::sregex_iterator(); ++it) {
  28. pos_len.push_back(std::make_pair(it->position(), it->length() ) );
  29. std::cout << it->position() << " " << it->length() << " : " << it->str()
  30. << std::endl;
  31. }
  32. for (std::vector<std::pair<int,int>>::iterator vit = pos_len.begin(); vit != pos_len.end(); ++vit ) {
  33. std::pair<int,int> p;
  34. p = *vit;
  35. cout << (*vit).first << "," << (*vit).second << endl;
  36. cout << p.first << "," << p.second << endl;
  37. }
  38. #ifdef RX1
  39. if (std::regex_match(input, match, integer)) {
  40. std::cout << "integer" << std::endl;
  41. for (int i = 0; i < match.size(); ++i) {
  42. std::cout << "match " << i << " (" << match[i] << ") At "
  43. << match.position(i) << " of " << match.length(i) << " chars."
  44. << std::endl;
  45. }
  46. for (std::smatch::iterator im = match.begin(); im != match.end(); ++im) {
  47. std::cout << "matches:" << *im << std::endl;
  48. }
  49. } else {
  50. std::cout << "Invalid input" << std::endl;
  51. }
  52. int offset = 0;
  53. while (std::regex_search(input, match, integer)) {
  54. std::cout << "input: [" << input << "]" << std::endl;
  55. std::cout << offset << " match len " << match.length(0) << std::endl;
  56. for (int i = 0; i < match.size(); ++i) {
  57. std::cout << "match " << i << " (" << match[i] << ") At "
  58. << offset + match.position(i) << " of " << match.length(i)
  59. << " chars." << std::endl;
  60. }
  61. for (auto x : match) {
  62. std::cout << x << " ";
  63. }
  64. std::cout << std::endl;
  65. input = match.suffix().str();
  66. offset += match.length(0) + match.prefix(0).size();
  67. }
  68. #endif
  69. }
  70. }