Skip to content

Commit f0ecfbf

Browse files
committed
Adding String.contains?
Detect whether a string contains another string.
1 parent ffdf9e9 commit f0ecfbf

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

lib/elixir/lib/string.ex

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -845,4 +845,29 @@ defmodule String do
845845

846846
def ends_with?(string, suffix), do: ends_with?(string, [ suffix ])
847847

848+
@doc """
849+
Returns true if `string` contains match, otherwise false.
850+
`matches` can be either a single match of a list of matches.
851+
852+
## Examples
853+
854+
iex> String.contains? "elixir of life", "of"
855+
true
856+
iex> String.contains? "elixir of life", ["life", "death"]
857+
true
858+
iex> String.contains? "elixir of life", ["death", "mercury"]
859+
false
860+
861+
"""
862+
def contains?(string, matches) when is_list(matches) do
863+
Enum.any? matches, fn match ->
864+
case :binary.matches(string, match) do
865+
[_] -> true
866+
[] -> false
867+
end
868+
end
869+
end
870+
871+
def contains?(string, match), do: contains?(string, [ match ])
872+
848873
end

lib/elixir/test/elixir/string_test.exs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,4 +303,13 @@ defmodule StringTest do
303303
refute String.ends_with? "エリクシア", "仙丹"
304304
end
305305

306+
test :contains? do
307+
assert String.contains? "elixir of life", "of"
308+
assert String.contains? "エリクシア", "シ"
309+
assert String.contains? "elixir of life", ["mercury", "life"]
310+
refute String.contains? "exlixir of life", "death"
311+
refute String.contains? "エリクシア", "仙"
312+
refute String.contains? "elixir of life", ["death", "mercury", "eternal life"]
313+
end
314+
306315
end

0 commit comments

Comments
 (0)