1
0
Fork 0
mirror of https://github.com/NixOS/nix synced 2025-07-03 02:01:48 +02:00

replace own regex class with std::regex

This commit is contained in:
Alexander Ried 2016-10-18 20:21:21 +02:00
parent ae8884b949
commit b05b98df75
5 changed files with 14 additions and 94 deletions

View file

@ -1,50 +0,0 @@
#include "regex.hh"
#include "types.hh"
#include <algorithm>
namespace nix {
Regex::Regex(const string & pattern, bool subs)
{
/* Patterns must match the entire string. */
int err = regcomp(&preg, ("^(" + pattern + ")$").c_str(), (subs ? 0 : REG_NOSUB) | REG_EXTENDED);
if (err) throw RegexError(format("compiling pattern %1%: %2%") % pattern % showError(err));
nrParens = subs ? std::count(pattern.begin(), pattern.end(), '(') : 0;
}
Regex::~Regex()
{
regfree(&preg);
}
bool Regex::matches(const string & s)
{
int err = regexec(&preg, s.c_str(), 0, 0, 0);
if (err == 0) return true;
else if (err == REG_NOMATCH) return false;
throw Error(format("matching string %1%: %2%") % s % showError(err));
}
bool Regex::matches(const string & s, Subs & subs)
{
regmatch_t pmatch[nrParens + 2];
int err = regexec(&preg, s.c_str(), nrParens + 2, pmatch, 0);
if (err == 0) {
for (unsigned int n = 2; n < nrParens + 2; ++n)
if (pmatch[n].rm_eo != -1)
subs[n - 2] = string(s, pmatch[n].rm_so, pmatch[n].rm_eo - pmatch[n].rm_so);
return true;
}
else if (err == REG_NOMATCH) return false;
throw Error(format("matching string %1%: %2%") % s % showError(err));
}
string Regex::showError(int err)
{
char buf[256];
regerror(err, &preg, buf, sizeof(buf));
return string(buf);
}
}

View file

@ -1,29 +0,0 @@
#pragma once
#include "types.hh"
#include <sys/types.h>
#include <regex.h>
#include <map>
namespace nix {
MakeError(RegexError, Error)
class Regex
{
public:
Regex(const string & pattern, bool subs = false);
~Regex();
bool matches(const string & s);
typedef std::map<unsigned int, string> Subs;
bool matches(const string & s, Subs & subs);
private:
unsigned nrParens;
regex_t preg;
string showError(int err);
};
}