aboutsummaryrefslogtreecommitdiff
path: root/tests/regex/driver.cxx
blob: fb41ba26612e8fc38d089e94298c7beb2957edbd (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// file      : tests/regex/driver.cxx -*- C++ -*-
// copyright : Copyright (c) 2014-2018 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

#include <cassert>

#ifndef __cpp_lib_modules
#include <string>
#include <iostream>
#include <exception>
#endif

// Other includes.

#ifdef __cpp_modules
#ifdef __cpp_lib_modules
import std.core;
import std.io;
import std.regex; // @@ MOD TODO: shouldn't be necessary (re-export).
#endif
import butl.regex;
import butl.utility; // operator<<(ostream, exception)
#else
#include <libbutl/regex.mxx>
#include <libbutl/utility.mxx>
#endif

using namespace std;
using namespace butl;

// Usage: argv[0] [-ffo] [-fnc] [-m] <string> <regex> <format>
//
// Perform substitution of matched substrings with formatted replacement
// strings using regex_replace_*() functions. If the string matches the regex
// then print the replacement to STDOUT and exit with zero code. Exit with
// code one if it doesn't match, and with code two on failure (print error
// description to STDERR).
//
// -ffo
//    Use format_first_only replacement flag.
//
// -fnc
//    Use format_no_copy replacement flag.
//
// -m
//    Match the entire string, rather than its sub-strings.
//
int
main (int argc, const char* argv[])
try
{
  regex_constants::match_flag_type fl (regex_constants::match_default);

  int i (1);
  bool match (false);
  for (; i != argc; ++i)
  {
    string op (argv[i]);

    if (op == "-ffo")
      fl |= regex_constants::format_first_only;
    else if (op == "-fnc")
      fl |= regex_constants::format_no_copy;
    else if (op == "-m")
      match = true;
    else
      break;
  }

  assert (i + 3 == argc);

  string s   (argv[i++]);
  regex  re  (argv[i++]);
  string fmt (argv[i]);

  auto r (match
          ? regex_replace_match (s, re, fmt)
          : regex_replace_search (s, re, fmt, fl));

  if (r.second)
    cout << r.first << endl;

  return r.second ? 0 : 1;
}
catch (const regex_error& e)
{
  cerr << "invalid regex" << e << endl; // Print sanitized.
  return 2;
}
catch (const exception& e)
{
  cerr << e << endl;
  return 2;
}