]> git.tdb.fi Git - libs/core.git/blob - source/strings/regmatch.h
Use string::size_type rather than unsigned to store string offsets
[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                 typedef std::string::size_type size_type;
28
29                 bool match;        //< Whether or not this group matched
30                 size_type begin;   //< First offset of the match
31                 size_type end;     //< One-past-last offset
32                 size_type length;  //< Length of the match (end-begin)
33                 std::string str;   //< The part of the string that matched
34
35                 Group(): match(false) { }
36                 operator bool() const { return match; }
37         };
38
39         typedef std::vector<Group> GroupArray;
40
41 private:
42         GroupArray groups;
43
44 public:
45         /** Constructs a RegMatch representing a non-match. */
46         RegMatch() { }
47
48         /** Constructs a new RegMatch from a string and groups.  The length and str
49         members of each group are computed and need not be set.  Intended to be used
50         by the Regex class. */
51         RegMatch(const std::string &, const std::vector<Group> &);
52
53         /** Returns a reference to a single group in the match. */
54         const Group &group(unsigned) const;
55
56         /** Returns true if the RegMatch object represents a non-match. */
57         bool empty() const { return groups.empty(); }
58
59         /** Returns the number of groups in this match. */
60         unsigned size() const { return groups.size(); }
61
62         /** Returns the begin offset of the whole match. */
63         unsigned begin() const { return groups.empty() ? 0 : groups[0].begin; }
64
65         /** Returns the end offset of the whole match. */
66         unsigned end() const { return groups.empty() ? 0 : groups[0].end; }
67
68         /** Shorthand for the group() function. */
69         const Group &operator[](unsigned i) const { return group(i); }
70
71         operator bool() const { return !empty(); }
72 };
73
74 } // namespace Msp
75
76 #endif