neuone

neuone

Getting the year out of a list of strings

I’m currently working on an application that require me to get the year out of a label.
They appear in different ways. It’s never consistent:

  examples = [
    "February 2015 Part 1",
    "2014 Part 2 February",
    "February 2015",
    "2015 Feb"
  ]

I need to separate them out so the year and label is like this

  expected_result = [
    %{"label" => "February Part 1", "year" => "2015"},
    %{"label" => "Part 2 February", "year" => "2014"},
    %{"label" => "February", "year" => "2015"},
    %{"label" => "Feb", "year" => "2015"}
  ]

Here is my implementation

defmodule ViewHelper do

  def get_label_with_year(sentence) do
    list_of_words = String.split(sentence, " ")

    year  = get_year(list_of_words)

    label =
      list_of_words
      |> Enum.reject(fn(word) -> word == year end)
      |> Enum.join(" ")

    %{}
    |> Map.put_new("label", label)
    |> Map.put_new("year", year)
  end


  def get_year(list_of_words) do
    [year] = list_of_words
              |> Enum.map(fn(x) -> Integer.parse(x) end)
              |> Enum.filter(fn(x) -> is_tuple(x) end)
              |> Enum.filter(fn({num, _}) -> String.length(to_string(num)) == 4 end)
              |> Enum.map(fn({num, _}) -> to_string(num) end)
     year
  end


end

and my test file

defmodule ViewHelperTest do
  use ExUnit.Case
  doctest ViewHelper

  test "get_label_with_year" do

  examples = [
    "February 2015 Part 1",
    "2014 Part 2 February",
    "February 2015",
    "2015 Feb"
  ]

  expected_result = [
    %{"label" => "February Part 1", "year" => "2015"},
    %{"label" => "Part 2 February", "year" => "2014"},
    %{"label" => "February", "year" => "2015"},
    %{"label" => "Feb", "year" => "2015"}
  ]

  my_test = Enum.map(examples, fn(x) -> ViewHelper.get_label_with_year(x) end)

  assert  my_test == expected_result

  end


end

Everything works. However…
I feel like this implementation is not the best way of writing this.
Could this be written differently so its easier to read? Am I overthinking this?

My intuition tells me this could be written differently so its much easier to understand in the future OR for someone else who will eventually look at this code. Looking for feedback and/or concepts on how to approach this differently (i.e. pattern matching, reducer)

Marked As Solved

amnu3387

amnu3387

One other way that only requires you to run the regex once per string is:

[pre, year, post] = Regex.run(~r/(.*)(\d{4})(.*)/, "February 2015 Part 1", capture: :all_but_first)
%{
   "label" => String.trim(String.trim(pre) <> " " <> String.trim(post)),
   "year" => year
}

Also Liked

kokolegorille

kokolegorille

Maybe simply Regex?

iex> capture_year = fn label -> Regex.named_captures ~r/(?<year>\d{4})/, label end 
iex> examples |> Enum.map(&capture_year.(&1))
[
  %{"year" => "2015"}, 
  %{"year" => "2014"},
  %{"year" => "2015"},
  %{"year" => "2015"}
]

Just adapt the output.

alco

alco

The most efficient solution would be built around binary pattern matching and creating as little extra garbage as possible.

In you solution, the call to String.split creates a bunch of new strings and each Enum.* call creates a new list.

Here’s my attempt at solving this problem:

defmodule FindYear do
  def extract_year(string), do: find_and_extract_year(string, 0, string)

  defp find_and_extract_year("", _position, whole_string),
    do: %{
      "year" => :not_found,
      "label" => whole_string
    }

  defp find_and_extract_year(<<d1, d2, d3, d4>> <> suffix, position, whole_string)
       when d1 in ?1..?9 and d2 in ?0..?9 and d3 in ?0..?9 and d4 in ?0..?9 do
    prefix = :binary.part(whole_string, {0, position})

    %{
      "year" => <<d1, d2, d3, d4>>,
      "label" => merge_and_trim(prefix, suffix)
    }
  end

  defp find_and_extract_year(<<_>> <> rest, position, whole_string),
    do: find_and_extract_year(rest, position + 1, whole_string)

  defp merge_and_trim("", rest), do: String.trim_leading(rest)
  defp merge_and_trim(prefix, ""), do: String.trim_trailing(prefix)
  defp merge_and_trim(prefix, " " <> suffix), do: prefix <> suffix
end

The basic idea is to walk the input string 1 byte at a time looking for a sequence of 4 consecutive digits. As soon as one is found, we extract the prefix that precedes the year and concatenate it with the remainder of the string.

Note that this code has a number of assumptions: it expects ASCII-only text, the year is assumed to be any 4-digit sequence that starts with a digit from 1 to 9, it expects only one year in the string, and all words are assumed to be split using a single space.

On the one hand, this solution is quite specific to the provided list of examples but, on the other hand, all the assumptions are pretty obvious from the code itself, without any documentation around it.

neuone

neuone

@amnu3387 :+1: That solution simplifies it down even further.

I’m also just posting from the docs what Regex states about capture :all_but_first for anyone in the future who reads this.

Captures
Many functions in this module handle what to capture in a regex match via the :capture option. The supported values are:

:all_but_first - all but the first matching subpattern, i.e. all explicitly captured subpatterns, but not the complete matching part of the string

Here are some other :capture options for future reference (source)

  • :all - all captured subpatterns including the complete matching string (this is the default)
  • :first - only the first captured subpattern, which is always the complete matching part of the string; all explicitly captured subpatterns are discarded
  • :all_but_first - all but the first matching subpattern, i.e. all explicitly captured subpatterns, but not the complete matching part of the string
  • :none - does not return matching subpatterns at all
  • :all_names - captures all names in the Regex
  • list(binary) - a list of named captures to capture

Its fun to see where it started and the variations being proposed. So many ways to approach it.

Where Next?

Popular in Questions Top

Tee
can someone please explain to me how Enum.reduce works with maps
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
vac
Hi, I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29603 241
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement