Skip to content

Commit 22627c4

Browse files
author
José Valim
committed
Merge pull request #1188 from josephwilk/string-contains
Adding String.contains?
2 parents 6e95973 + ae8def3 commit 22627c4

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

lib/elixir/lib/string.ex

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -845,4 +845,27 @@ 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+
case :binary.match(string, matches) do
864+
:nomatch -> false
865+
_ -> true
866+
end
867+
end
868+
869+
def contains?(string, match), do: contains?(string, [ match ])
870+
848871
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)