Unexpected behavior of match_results::prefix

I'm noticing some unexpected behavior of the match_results::prefix function with visual studio 2010. I wondering if someone could run this example with VS2013 or another compiler, and let me know if the behavior is the same.

The stream operations work fine and the printed prefix is exactly what I expect. However, any attempt to store the prefix into a std::string is resulting in a different string. This particular program crashes for me because the last attempt to copy and store prefix crashes. Either I do not understand what prefix() is for, or there is a bug in the STL being used by visual studio. If the STL is working properly here, then I have no idea what the prefix function is for or why an str() method is provided. Please advise if you have any suggestions.

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
28
29
30
31
32
33
void TestRegExSearchStorePrefix()
{
  std::string s ("this subject has a submarine as a subsequence");
  std::string expr("\\b(sub)([^ ]*)");
  std::string p;
  std::string pstr;
  std::smatch m;
  std::regex e (expr);   // matches words beginning by "sub"

  std::cout << "Target sequence: " << s << std::endl;
  std::cout << "Regular expression: " << expr << std::endl;
  std::cout << "The following matches and submatches were found:" << std::endl;

  while (std::regex_search (s,m,e)) {
    auto x = std::begin(m);
    auto end = std::end(m);
    for (; x != end; ++x) 
        std::cout << x->str() << " ";
    std::cout << std::endl;
    std::cout <<  m.prefix() << " " << std::endl;  //prints this, has a, as a which is expected
    std::cout <<  m.suffix() << " " << std::endl;
    s = m.suffix();
    p += m.prefix(); // p = has instead of this the first time through
    // This crashes on the last iteration.  Seems like setting to a std::string is not doing the same thing as the stream
    // It looks like the first word of suffix
    pstr += m.prefix().str(); 
  }
}

int main()
{
    TestRegExSearchStorePrefix();
}


Here is some output that shows that the output of prefix to the stream works. I just don't understand why getting the prefix into a string object is difficult.
Target sequence: this subject has a submarine as a subsequence
Regular expression: \b(sub)([^ ]*)
The following matches and submatches were found:
subject sub ject
this
 has a submarine as a subsequence
submarine sub marine
 has a
 as a subsequence
subsequence sub sequence
 as a

Last edited on
Topic archived. No new replies allowed.