summaryrefslogtreecommitdiff
path: root/libcutl/cutl/re/re.txx
blob: 174e0d4e7c35231b83d4a08fcc589766662bba1a (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
// file      : cutl/re/re.txx
// copyright : Copyright (c) 2009-2013 Code Synthesis Tools CC
// license   : MIT; see accompanying LICENSE file

namespace cutl
{
  namespace re
  {
    //
    // basic_regexsub
    //
    template <typename C>
    void basic_regexsub<C>::
    init (string_type const& s)
    {
      string_type r;
      typename string_type::size_type p (parse (s, 0, r));
      regex_ = r;
      p = parse (s, p, sub_);
      if (p + 1 < s.size ())
        throw basic_format<C> (s, "junk after third delimiter");
    }

    //
    // parse()
    //
    template <typename C>
    typename std::basic_string<C>::size_type
    parse (std::basic_string<C> const& s,
           typename std::basic_string<C>::size_type p,
           std::basic_string<C>& r)
    {
      r.clear ();
      typename std::basic_string<C>::size_type n (s.size ());

      if (p >= n)
        throw basic_format<C> (s, "empty expression");

      char d (s[p++]);

      for (; p < n; ++p)
      {
        if (s[p] == d)
          break;

        if (s[p] == '\\')
        {
          if (++p < n)
          {
            // Pass the escape sequence through unless it is the delimiter.
            //
            if (s[p] != d)
              r += '\\';

            r += s[p];
          }
          // else {We ran out of stuff before finding the delimiter.}
        }
        else
          r += s[p];
      }

      if (p == n)
        throw basic_format<C> (s, "missing closing delimiter");

      return p;
    }
  }
}