Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pipe the results of Enum.join into Regex.scan in Elixir?

Tags:

elixir

From the docs on pipe operator, I see "The |> symbol used in the snippet above is the pipe operator: it simply takes the output from the expression on its left side and passes it as the first argument to the function call on its right side.".

But if I have a string that I split, then join it and want to feed that joined string into Regex.scan below, how do I do it? I get a compiled error unhandled &1 outside of a capture when I try to run the below...And I think this is due to my lack of understanding on how to capture a pipe operator output and use it as an argument.

string
|> String.split(" ")  
## some other operations here to operate on split string omitted for clarity
|> Enum.join
|> Regex.scan(~r/[A-Z]/, &1)
|> List.flatten
|> Enum.join
like image 571
Nona Avatar asked Dec 11 '22 16:12

Nona


1 Answers

You can create an anonymous function using & and pipe into it:

"Hello World!"
|> String.split(" ")
|> Enum.join
|> (&Regex.scan(~r/[A-Z]/, &1)).()
|> List.flatten
|> Enum.join
|> IO.inspect

Output:

"HW"
like image 97
Dogbert Avatar answered Mar 03 '23 15:03

Dogbert