From 976df480c918f050608f7a23a4a21415c43475c3 Mon Sep 17 00:00:00 2001 From: Eelco Dolstra Date: Tue, 25 Nov 2014 11:47:06 +0100 Subject: Add a primop for regular expression pattern matching MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The function ‘builtins.match’ takes a POSIX extended regular expression and an arbitrary string. It returns ‘null’ if the string does not match the regular expression. Otherwise, it returns a list containing substring matches corresponding to parenthesis groups in the regex. The regex must match the entire string (i.e. there is an implied "^$" around the regex). For example: match "foo" "foobar" => null match "foo" "foo" => [] match "f(o+)(.*)" "foooobar" => ["oooo" "bar"] match "(.*/)?([^/]*)" "/dir/file.nix" => ["/dir/" "file.nix"] match "(.*/)?([^/]*)" "file.nix" => [null "file.nix"] The following example finds all regular files with extension .nix or .patch underneath the current directory: let findFiles = pat: dir: concatLists (mapAttrsToList (name: type: if type == "directory" then findFiles pat (dir + "/" + name) else if type == "regular" && match pat name != null then [(dir + "/" + name)] else []) (readDir dir)); in findFiles ".*\\.(nix|patch)" (toString ./.) --- tests/lang/eval-okay-regex-match.exp | 1 + tests/lang/eval-okay-regex-match.nix | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 tests/lang/eval-okay-regex-match.exp create mode 100644 tests/lang/eval-okay-regex-match.nix (limited to 'tests') diff --git a/tests/lang/eval-okay-regex-match.exp b/tests/lang/eval-okay-regex-match.exp new file mode 100644 index 000000000000..27ba77ddaf61 --- /dev/null +++ b/tests/lang/eval-okay-regex-match.exp @@ -0,0 +1 @@ +true diff --git a/tests/lang/eval-okay-regex-match.nix b/tests/lang/eval-okay-regex-match.nix new file mode 100644 index 000000000000..ae6501532d11 --- /dev/null +++ b/tests/lang/eval-okay-regex-match.nix @@ -0,0 +1,26 @@ +with builtins; + +let + + matches = pat: s: match pat s != null; + + splitFN = match "((.*)/)?([^/]*)\\.(nix|cc)"; + +in + +assert matches "foobar" "foobar"; +assert matches "fo*" "f"; +assert !matches "fo+" "f"; +assert matches "fo*" "fo"; +assert matches "fo*" "foo"; +assert matches "fo+" "foo"; +assert matches "fo{1,2}" "foo"; +assert !matches "fo{1,2}" "fooo"; +assert !matches "fo*" "foobar"; + +assert match "(.*)\\.nix" "foobar.nix" == [ "foobar" ]; + +assert splitFN "/path/to/foobar.nix" == [ "/path/to/" "/path/to" "foobar" "nix" ]; +assert splitFN "foobar.cc" == [ null null "foobar" "cc" ]; + +true -- cgit 1.4.1