aboutsummaryrefslogtreecommitdiff
path: root/src/libutil
diff options
context:
space:
mode:
Diffstat (limited to 'src/libutil')
-rw-r--r--src/libutil/regex.cc23
-rw-r--r--src/libutil/regex.hh9
2 files changed, 28 insertions, 4 deletions
diff --git a/src/libutil/regex.cc b/src/libutil/regex.cc
index 36c8458ce..84274b3e1 100644
--- a/src/libutil/regex.cc
+++ b/src/libutil/regex.cc
@@ -1,13 +1,16 @@
#include "regex.hh"
#include "types.hh"
+#include <algorithm>
+
namespace nix {
-Regex::Regex(const string & pattern)
+Regex::Regex(const string & pattern, bool subs)
{
/* Patterns must match the entire string. */
- int err = regcomp(&preg, ("^(" + pattern + ")$").c_str(), REG_NOSUB | REG_EXTENDED);
- if (err) throw Error(format("compiling pattern ‘%1%’: %2%") % pattern % showError(err));
+ 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()
@@ -23,6 +26,20 @@ bool Regex::matches(const string & s)
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];
diff --git a/src/libutil/regex.hh b/src/libutil/regex.hh
index aa012b721..53e31f4ed 100644
--- a/src/libutil/regex.hh
+++ b/src/libutil/regex.hh
@@ -5,16 +5,23 @@
#include <sys/types.h>
#include <regex.h>
+#include <map>
+
namespace nix {
+MakeError(RegexError, Error)
+
class Regex
{
public:
- Regex(const string & pattern);
+ 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);
};