Otoma
Otoma

Reputation: 171

Pattern matching on strings of different length

I have a list of strings:

 list1 = ["aaa_1_bbb_1326778", "aaa_629_bbb_37", "aaa_2254354_bbb_3997"]

How can I easily extract both numbers from each item except by using Regexp?

Enum.map(list1, fn(x) ->
  # 
end)

Is there any solution something like pattern matching?

Upvotes: 0

Views: 569

Answers (1)

Dogbert
Dogbert

Reputation: 222080

If the format is always 4 things separated by underscores and the second and fourth are integers, which are the things you want, I'd use String.split and pattern matching like this:

list1 = ["aaa_1_bbb_1326778", "aaa_629_bbb_37", "aaa_2254354_bbb_3997"]

Enum.map(list1, fn(x) ->
  [_, a, _, b] = String.split(x, "_")
  {String.to_integer(a), String.to_integer(b)}
end) |> IO.inspect

Output:

[{1, 1326778}, {629, 37}, {2254354, 3997}]

While you could use more pattern matching and less splitting here, you'd need to define some functions and use recursion, which I wouldn't personally do as long as String.split exists and fits the use case.

Upvotes: 3

Related Questions