1 //===-- Regex.cpp - Regular Expression matcher implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a POSIX regular expression matcher.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/Regex.h"
15 #include "llvm/Support/ErrorHandling.h"
16 #include "llvm/Support/raw_ostream.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "regex_impl.h"
22 Regex::Regex(const StringRef ®ex, unsigned Flags) {
24 preg = new llvm_regex();
25 preg->re_endp = regex.end();
26 if (Flags & IgnoreCase)
30 error = llvm_regcomp(preg, regex.data(), flags|REG_EXTENDED|REG_PEND);
38 bool Regex::isValid(std::string &Error) {
42 size_t len = llvm_regerror(error, preg, NULL, 0);
45 llvm_regerror(error, preg, &Error[0], len);
49 /// getNumMatches - In a valid regex, return the number of parenthesized
50 /// matches it contains.
51 unsigned Regex::getNumMatches() const {
55 bool Regex::match(const StringRef &String, SmallVectorImpl<StringRef> *Matches){
56 unsigned nmatch = Matches ? preg->re_nsub+1 : 0;
58 // pmatch needs to have at least one element.
59 SmallVector<llvm_regmatch_t, 8> pm;
60 pm.resize(nmatch > 0 ? nmatch : 1);
62 pm[0].rm_eo = String.size();
64 int rc = llvm_regexec(preg, String.data(), nmatch, pm.data(), REG_STARTEND);
66 if (rc == REG_NOMATCH)
69 // regexec can fail due to invalid pattern or running out of memory.
76 if (Matches) { // match position requested
79 for (unsigned i = 0; i != nmatch; ++i) {
80 if (pm[i].rm_so == -1) {
81 // this group didn't match
82 Matches->push_back(StringRef());
85 assert(pm[i].rm_eo > pm[i].rm_so);
86 Matches->push_back(StringRef(String.data()+pm[i].rm_so,
87 pm[i].rm_eo-pm[i].rm_so));