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