]> git.tdb.fi Git - libs/core.git/blob - source/strings/regmatch.h
Improve exceptions for Regex and RegMatch
[libs/core.git] / source / strings / regmatch.h
1 #ifndef MSP_STRINGS_REGMATCH_H_
2 #define MSP_STRINGS_REGMATCH_H_
3
4 #include <string>
5 #include <vector>
6
7 namespace Msp {
8
9 /**
10 This class stores the result of a Regex being matched against a string.  If the
11 match was successful, the RegMatch object evaluates to true.
12
13 A RegMatch representing a successful match has one or more groups, indicating
14 matching parts of the string.  The first group (with index 0) indicates the
15 part matched by the whole regex.  Further groups, if present, indicate parts
16 matched by subregexes.  These are ordered from left to right, by the opening
17 parenthesis of the subregex.
18 */
19 class RegMatch
20 {
21 public:
22         /**
23         A single subregex of the match.
24         */
25         struct Group
26         {
27                 bool match;       //< Whether or not this group matched
28                 unsigned begin;   //< First offset of the match
29                 unsigned end;     //< One-past-last offset
30                 unsigned length;  //< Length of the match (end-begin)
31                 std::string str;  //< The part of the string that matched
32
33                 Group(): match(false) { }
34                 operator bool() const { return match; }
35         };
36
37         typedef std::vector<Group> GroupArray;
38
39 private:
40         GroupArray groups;
41
42 public:
43         /** Constructs a RegMatch representing a non-match. */
44         RegMatch() { }
45
46         /** Constructs a new RegMatch from a string and groups.  The length and str
47         members of each group are computed and need not be set.  Intended to be used
48         by the Regex class. */
49         RegMatch(const std::string &, const std::vector<Group> &);
50
51         /** Returns a reference to a single group in the match. */
52         const Group &group(unsigned) const;
53
54         /** Returns true if the RegMatch object represents a non-match. */
55         bool empty() const { return groups.empty(); }
56
57         /** Returns the number of groups in this match. */
58         unsigned size() const { return groups.size(); }
59
60         /** Returns the begin offset of the whole match. */
61         unsigned begin() const { return groups.empty() ? 0 : groups[0].begin; }
62
63         /** Returns the end offset of the whole match. */
64         unsigned end() const { return groups.empty() ? 0 : groups[0].end; }
65
66         /** Shorthand for the group() function. */
67         const Group &operator[](unsigned i) const { return group(i); }
68
69         operator bool() const { return !empty(); }
70 };
71
72 } // namespace Msp
73
74 #endif