From 104e55bb7f593b1ac3c54ffda48a9d72af7fbe6b Mon Sep 17 00:00:00 2001 From: Eelco Dolstra Date: Fri, 3 Oct 2014 18:47:16 +0200 Subject: nix-env: Add regular expression support in selectors So you can now do things like: $ nix-env -qa '.*zip.*' $ nix-env -qa '.*(firefox|chromium).*' --- src/libutil/regex.cc | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/libutil/regex.cc (limited to 'src/libutil/regex.cc') diff --git a/src/libutil/regex.cc b/src/libutil/regex.cc new file mode 100644 index 000000000..36c8458ce --- /dev/null +++ b/src/libutil/regex.cc @@ -0,0 +1,33 @@ +#include "regex.hh" +#include "types.hh" + +namespace nix { + +Regex::Regex(const string & pattern) +{ + /* 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)); +} + +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)); +} + +string Regex::showError(int err) +{ + char buf[256]; + regerror(err, &preg, buf, sizeof(buf)); + return string(buf); +} + +} -- cgit v1.2.3