Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir - Check if string includes a sub-string

Tags:

elixir

How to check if a String includes another String in Elixir? This is different from How to find index of a substring?.

Something like:

String.includes("hello", "lo")
#=> true
like image 458
Sheharyar Avatar asked Oct 25 '16 23:10

Sheharyar


2 Answers

String.contains?(string, contents)

Checks if string contains any of the given contents.

Example:

iex> String.contains? "elixir of life", "of"
true
iex> String.contains? "elixir of life", ["life", "death"]
true
iex> String.contains? "elixir of life", ["venus", "mercury"]
false
like image 63
Sheharyar Avatar answered Nov 05 '22 21:11

Sheharyar


You can also use =~:

"elixir of life" =~ "of"
# true

or in tests with assertions:

assert "elixir of life" =~ "of"

or with a regular expression:

"elixir of life" =~ ~r/of/
# true

Excerpt from the documentation: Matches the term on the left against the regular expression or string on the right.

Returns true if left matches right (if it's a regular expression) or contains right (if it's a string).

like image 27
Joe Eifert Avatar answered Nov 05 '22 19:11

Joe Eifert