match
lib.strings.match
Primop
Docs pulled from | This Revision | 14 minutes ago
Nix manual
Takes 2 arguments
regex, str
Returns a list if the extended POSIX regular
expression
regex matches str precisely, otherwise returns null. Each item
in the list is a regex group.
builtins.match "ab" "abc"
Evaluates to null.
builtins.match "abc" "abc"
Evaluates to [ ].
builtins.match "a(b)(c)" "abc"
Evaluates to [ "b" "c" ].
builtins.match "[[:space:]]+([[:upper:]]+)[[:space:]]+" " FOO "
Evaluates to [ "FOO" ].
Noogle detected
Detected Type
match :: String -> String -> Bool
Implementation
This function is implemented in c++ and is part of the native nix runtime.
void prim_match(EvalState & state, const PosIdx pos, Value ** args, Value & v)
{
auto re = state.forceStringNoCtx(*args[0], pos, "while evaluating the first argument passed to builtins.match");
try {
auto regex = state.regexCache->get(re);
NixStringContext context;
const auto str =
state.forceString(*args[1], context, pos, "while evaluating the second argument passed to builtins.match");
std::cmatch match;
if (!std::regex_match(str.begin(), str.end(), match, *regex)) {
v.mkNull();
return;
}
// the first match is the whole string
auto list = state.buildList(match.size() - 1);
for (const auto & [i, v2] : enumerate(list))
if (!match[i + 1].matched)
v2 = &Value::vNull;
else
v2 = mkString(state, match[i + 1]);
v.mkList(list);
} catch (std::regex_error & e) {
if (e.code() == std::regex_constants::error_space) {
// limit is _GLIBCXX_REGEX_STATE_LIMIT for libstdc++
state.error<EvalError>("memory limit exceeded by regular expression '%s'", re).atPos(pos).debugThrow();
} else
state.error<EvalError>("invalid regular expression '%s'", re).atPos(pos).debugThrow();
}
}