mirror of
https://github.com/NixOS/nix
synced 2025-07-08 11:03:54 +02:00
Add a primop for regular expression pattern matching
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 "^<pat>$" 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 ./.)
This commit is contained in:
parent
4e340a983f
commit
976df480c9
5 changed files with 84 additions and 5 deletions
1
tests/lang/eval-okay-regex-match.exp
Normal file
1
tests/lang/eval-okay-regex-match.exp
Normal file
|
@ -0,0 +1 @@
|
|||
true
|
26
tests/lang/eval-okay-regex-match.nix
Normal file
26
tests/lang/eval-okay-regex-match.nix
Normal file
|
@ -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
|
Loading…
Add table
Add a link
Reference in a new issue