diff --git a/lib/default.nix b/lib/default.nix index f62de95a..cda082e3 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -15,7 +15,9 @@ lib.makeExtensible (self: attrs = callLibs ./attrs.nix; os = callLibs ./devos; lists = callLibs ./lists.nix; + strings = callLibs ./strings.nix; inherit (attrs) mapFilterAttrs genAttrs' pathsToImportedAttrs concatAttrs; inherit (lists) pathsIn; + inherit (strings) rgxToString; }) diff --git a/lib/strings.nix b/lib/strings.nix new file mode 100644 index 00000000..56a0861d --- /dev/null +++ b/lib/strings.nix @@ -0,0 +1,20 @@ +{ lib, ... }: +{ + # returns matching part of _regex_ _string_; null indicates failure. + rgxToString = regex: string: + let + match = + let + head = lib.substring 0 1 regex; + sec = lib.substring 1 2 regex; + in + if head == "^" + || head == "." + || (sec == "*" || sec == "+" || sec == "?") + then builtins.match "(${regex}).*" string + else builtins.match ".*(${regex}).*" string; + in + if lib.isList match + then lib.head match + else null; +} diff --git a/tests/lib.nix b/tests/lib.nix index 249824e7..65559f8d 100644 --- a/tests/lib.nix +++ b/tests/lib.nix @@ -59,4 +59,11 @@ lib.runTests { f = false; }; }; + + testRgxToString = lib.testAllTrue [ + (rgxToString ".+x" "vxk" == "vx") + (rgxToString "^fo" "foo" == "fo") + (rgxToString "a?" "a" == "a") + (rgxToString "hat" "foohatbar" == "hat") + ]; }