input-int.cpp 2.4 KB

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