summaryrefslogtreecommitdiff
path: root/regex-search-example.cpp
blob: f77a56655c4b7b38c7a11cd19a27e8046fff04a3 (plain)
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
34
// regex_search example
// NOTE:
// std::regex_match matches the ENTIRE string
//   (as if with '^' and '$' anchors).
// Use std::regex_search to match partial strings.
#include <iostream>
#include <string>
#include <regex>

using namespace std;

int main ()
{
  string s ("synchronized chrysalis monochrome chromium chrX");
  smatch m;
  regex e ("\\b(chr)([^ ]*)");

  cout << "words starting with 'chr':" << endl;

  while (regex_search (s,m,e)) {
    // The regex contained 2 groups, hence 'm' will contain
    // Three items: [0] = Entire match
    //              [1] = The content of the first group ('chr')
    //              [2] = The content of the second group
    cout << "word: '" << m[0] << "'"
         << " suffix: '" << m[2] << "'" << endl;

    // To find the next match, search in the suffix
    // (the characters left after this match)
    s = m.suffix().str();
  }

  return 0;
}