Regex issues!

Below is my code to test the regex iterator.
I use word = "h??"
and word2 = "him hey hot got".
However, it reaches an error with cout << *it;
This is how I learned to output it, so I can't figure out why it is giving errors. Any help is greatly appreciated!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <regex>
#include <string>

using namespace std;

int main()
{
  string word, word2;

  cin >> word;
  cin >> word2;

  regex reg1(word, regex_constants::icase);

  sregex_iterator it(word2.begin(), word2.end(), reg1);
  sregex_iterator it_end;

  while(it != it_end)
  {
    cout << *it << endl;
    ++it;
  }


  return 0;
}
You seem to think that question marks mean "any character". That may be true in filename wildcards from the terminal, but in a regex a period means "any character". A question mark means "zero or one" of the preceding thing. So try entering "h.." and "him hey got hooray done" . It should print "him", "hey", "hoo".

Also, using >> with cin stops at the first space. Use getline to read a line.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <regex>
#include <string>
using namespace std;

int main() {
  string reStr, line;
  getline(cin, reStr);
  getline(cin, line);

  regex re(reStr, regex_constants::icase);

  sregex_iterator it(line.begin(), line.end(), re);
  sregex_iterator it_end;

  while (it != it_end)
  {
    cout << (*it).str() << '\n';  // *it is an smatch, which has a method called str()
    ++it;
  }
}

Last edited on
Topic archived. No new replies allowed.