Elixir-检查字符串是否包含子字符串

She*_*yar 2 elixir

如何检查一个字符串是否在Elixir中包含另一个字符串?这与如何查找子字符串的索引不同?。

就像是:

String.includes("hello", "lo")
#=> true
Run Code Online (Sandbox Code Playgroud)

She*_*yar 8

String.contains?(字符串,内容)

检查字符串是否包含任何给定的内容。

例:

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
Run Code Online (Sandbox Code Playgroud)


Joe*_*ert 5

您还可以使用=~:

"elixir of life" =~ "of"
# true
Run Code Online (Sandbox Code Playgroud)

或在带有断言的测试中:

assert "elixir of life" =~ "of"
Run Code Online (Sandbox Code Playgroud)

或使用正则表达式:

"elixir of life" =~ ~r/of/
# true
Run Code Online (Sandbox Code Playgroud)

文档摘录:将左侧的术语与右侧的正则表达式或字符串匹配。

如果 left 与 right 匹配(如果它是一个正则表达式)或包含 right(如果它是一个字符串),则返回 true。