lib: add rgxToString function

This commit is contained in:
Timothy DeHerrera 2021-03-14 21:40:49 -06:00
parent d51cd34fb7
commit d8068073c6
No known key found for this signature in database
GPG key ID: 8985725DB5B0C122
3 changed files with 29 additions and 0 deletions

View file

@ -15,7 +15,9 @@ lib.makeExtensible (self:
attrs = callLibs ./attrs.nix; attrs = callLibs ./attrs.nix;
os = callLibs ./devos; os = callLibs ./devos;
lists = callLibs ./lists.nix; lists = callLibs ./lists.nix;
strings = callLibs ./strings.nix;
inherit (attrs) mapFilterAttrs genAttrs' pathsToImportedAttrs concatAttrs; inherit (attrs) mapFilterAttrs genAttrs' pathsToImportedAttrs concatAttrs;
inherit (lists) pathsIn; inherit (lists) pathsIn;
inherit (strings) rgxToString;
}) })

20
lib/strings.nix Normal file
View file

@ -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;
}

View file

@ -59,4 +59,11 @@ lib.runTests {
f = false; f = false;
}; };
}; };
testRgxToString = lib.testAllTrue [
(rgxToString ".+x" "vxk" == "vx")
(rgxToString "^fo" "foo" == "fo")
(rgxToString "a?" "a" == "a")
(rgxToString "hat" "foohatbar" == "hat")
];
} }