我目前正在尝试迭代Mongo中的一个集合。为此,我使用这个正则表达式来过滤该集合。在某些情况下,正则表达式返回nil,在这种情况下,它会破坏List.first
,因为列表中没有任何内容。这会导致后面的问题。
我来自Ruby,在那里我可以做一个next unless recipient
,或者使用一个单独的操作符List&.first
,然后从那里开始。我在Elixir中如何做这件事呢?我主要感兴趣的是如果接收者的值为零,跳过当前的迭代。
recipient =
Regex.run(~r/(?<=recipient-).+\/*/, engagement["_id"])
|> List.first()
|> String.split("/")
|> List.first()
3条答案
按热度按时间bxfogqkk1#
If I understood you correctly, looks like you need start use
case
blocks, eg:OR
lnvxswe22#
作为case语句的替代方法,您可以使用函数子句的头部来匹配正则表达式的结果,即
nil
或match:在iex中:
听起来您可能希望使用Enum.reduce/3来过滤您的集合:
在iex中:
您也可以使用for编写:
mqkwyuun3#
TL;DR Use
for/1
comprehension filtering out unwanted input (everything that is not a list, having a binary head)As per documentation for
Regex.run/3
, it returns the typeThat said, one might use
List.wrap/1
to produce an empty list out ofnil
.Unfortunately, it would then blow up on
String.split/2
down the pipeline.That said, one might resort to
Regex.scan/3
instead ofRegex.run/3
that always returns a list.But all this looks like an XY problem. You stated
nil
.*That is impossible out of the box, but there are many workarounds.
Enum.reduce/3
with a reducer having two clausesEnum.map/2
followed byEnum.reject/2
for/1
comprehension filtering outnil
sI would vote for the latter.