我在凤凰城有一条需要用REGEX检查JSON参数的路由。 在我的日常工作中,我正在创建一个错误列表,以便在一个或多个正则表达式失败时在正文中报告。 但每当我运行代码时,我都会得到" FunctionClauseError" " Regex.match错误?"。我尝试过String.match,但是它们评估的功能相同。
这是我的代码:
def postServidor(conn, parameters) do
reasons = []
error = False
if not Regex.match?(~r/^(19[0-9]{2}|2[0-9]{3})-(0[1-9]|1[012])-([123]0|[012][1-9]|31)$/, Map.get(parameters, "data_nascimento")) do
{error, reasons} = {True, reasons ++ [%{Reason => "[data_nascimento] missing or failed to match API requirements. It should look like this: 1969-02-12"}]}
end
if not Regex.match?(~r/^([A-Z][a-z]+([ ]?[a-z]?['-]?[A-Z][a-z]+)*)$/, Map.get(parameters, "nome")) do
{error, reasons} = {True, reasons ++ [%{Reason => "[name] missing or failed to match API requirements. It should look like this: Firstname Middlename(optional) Lastname"}]}
end
if not Regex.match?(~r/^([A-Z][a-z]+([ ]?[a-z]?['-]?[A-Z][a-z]+)*)$/, Map.get(parameters, "nome_identificacao")) do
{error, reasons} = {True, reasons ++ [%{Reason => "[nome_identificacao] missing or failed to match API requirements. It should look like this: Firstname Middlename(optional) Lastname"}]}
end
if not Regex.match?(~r/\b[MF]{1}\b/, Map.get(parameters, "sexo")) do
{error, reasons} = {True, reasons ++ [%{Reason => "[sexo] missing or failed to match API requirements. It should look like this: M for male, F for female"}]}
end
if not Regex.match?( ~r/\b[0-9]+\b/, Map.get(parameters, "id_pessoa")) do
{error, reasons} = {True, reasons ++ [%{Reason => "[id_pessoa] missing or failed to match API requirements. It should be numeric. "}]}
end
if not Regex.match?(~r/\b[0-9]+\b/, Map.get(parameters, "matricula_interna")) do
{error, reasons} = {True, reasons ++ [%{Reason => "[matricula_interna] missing or failed to match API requirements. It should be numeric. "}]}
end
if not Regex.match?(~r/\b[0-9]+\b/, Map.get(parameters, "siape")) do
{error, reasons} = {True, reasons ++ [%{Reason => "[siape] missing or failed to match API requirements. It should be numeric. "}]}
end
if error = True do
json put_status(conn, 400),reasons
else
IO.puts("ok")
end
end
答案 0 :(得分:1)
Regex.match?/2
需要一个字符串作为其第二个参数。您使用Map.get/3
可能会返回该字符串,但如果在地图中找不到该键,则默认为nil
,这就是我猜测发生了什么。如果在地图中找不到密钥,则会将nil
传递给Regex.match?/2
,因为没有匹配的函数子句。您可以修复地图以正确使用密钥,也可以提供自己的默认字符串作为Map.get/3
的第三个参数。例如,Map.get(parameters, "data_nascimento", "some default")
。