summaryrefslogtreecommitdiff
path: root/regex-match-example.cpp
blob: ab71e66e94acf865243a989b9b0c5b15d79e231a (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
35
36
37
38
39
40
41
42
// regex_match 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>
#include <cassert>

using namespace std;

int main ()
{
  // should match - regex accepts the entire string
  bool b = regex_match("chromium",regex("chr.*"));
  assert(b);

  // should not match - regex does not accept entire
  // string, yet 'regex_match' requires entire input to match
  // (unlike regex_search).
  b = regex_match("chromium",regex("chr"));
  assert (!b);


  // match on 'char*' - use 'cmatch'
  const char cstr[] = "hello world 42";
  cmatch cm;
  regex re(".*?(\\d+)");
  b = regex_match (cstr,cm,re);
  assert(b);
  cout << "const char - matched number: " << cm[1] << endl;

  // match on 'string' - use 'smatch'
  const string s("hello world 41");
  smatch sm;
  b = regex_match (s,sm,re);
  assert(b);
  cout << "string - matched number: " << sm[1] << endl;

  return 0;
}