1 // Copyright 2015 Google Inc. All rights reserved.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 #ifndef BENCHMARK_RE_H_
16 #define BENCHMARK_RE_H_
18 #if defined(HAVE_STD_REGEX)
20 #elif defined(HAVE_GNU_POSIX_REGEX)
22 #elif defined(HAVE_POSIX_REGEX)
25 #error No regular expression backend was found!
33 // A wrapper around the POSIX regular expression API that provides automatic
37 Regex() : init_(false) {}
41 // Compile a regular expression matcher from spec. Returns true on success.
43 // On failure (and if error is not nullptr), error is populated with a human
44 // readable error message if an error occurs.
45 bool Init(const std::string& spec, std::string* error);
47 // Returns whether str matches the compiled regular expression.
48 bool Match(const std::string& str);
52 // Underlying regular expression object
53 #if defined(HAVE_STD_REGEX)
55 #elif defined(HAVE_POSIX_REGEX) || defined(HAVE_GNU_POSIX_REGEX)
58 #error No regular expression backend implementation available
62 #if defined(HAVE_STD_REGEX)
64 inline bool Regex::Init(const std::string& spec, std::string* error) {
66 re_ = std::regex(spec, std::regex_constants::extended);
69 } catch (const std::regex_error& e) {
77 inline Regex::~Regex() {}
79 inline bool Regex::Match(const std::string& str) {
83 return std::regex_search(str, re_);
87 inline bool Regex::Init(const std::string& spec, std::string* error) {
88 int ec = regcomp(&re_, spec.c_str(), REG_EXTENDED | REG_NOSUB);
91 size_t needed = regerror(ec, &re_, nullptr, 0);
92 char* errbuf = new char[needed];
93 regerror(ec, &re_, errbuf, needed);
95 // regerror returns the number of bytes necessary to null terminate
96 // the string, so we move that when assigning to error.
98 error->assign(errbuf, needed - 1);
110 inline Regex::~Regex() {
116 inline bool Regex::Match(const std::string& str) {
120 return regexec(&re_, str.c_str(), 0, nullptr, 0) == 0;
124 } // end namespace benchmark
126 #endif // BENCHMARK_RE_H_