我有这个正则表达式,应该从日志行中提取一些命名的捕获。如果第一个正则表达式失败,它应该转移到第二个正则表达式并尝试相反。所以基本上这是我目前的代码:
captures = Regex.named_captures(first_regex, log)
if captures == nil do
captures = Regex.named_captures(backup_regex, log)
end
我正在使用此方法来避免运行两个正则表达式,如果第一个匹配(在我的方案中足够)。这件事发出警告,说明the variable "captures" is unsafe as it has been set inside a case/cond/receive/if/&&/||. Please explicitly return the variable value instead.
我可以这样重写它,以便它停止发出警告:
captures =
case Regex.named_captures(squid_re, log) do
nil -> Regex.named_captures(dante_re, log)
{:username} -> # How do I return with username?
end
..但是,因为这是我使用elixir的第一天,我不知道如何将该用户名分配给captures
变量。有什么想法吗?
答案 0 :(得分:3)
对于这种特殊情况,您可以使用||
,因为对于nil
(和false
),||
将返回RHS的值,否则LHS:< / p>
captures = Regex.named_captures(first_regex, log) || Regex.named_captures(backup_regex, log)
如果你真的想使用case
,那么你就是这样做的:
captures = case Regex.named_captures(first_regex, log) do
nil -> Regex.named_captures(backup_regex, log)
captures -> captures
end
第二个模式将匹配任何值并将其值分配给captures
,您只需返回相同的值即可。如果代码与您发布的代码非常相似,我建议使用||
。