如何检查 Elixir 中的字符串是否为空
How to check if a string is blank in Elixir
我的意思是,如果字符串为空或仅包含空格,则该字符串为空白。
例如""
、" "
、"\n"
都是空白。
在Rails中,我们有.blank?
方法。
Elixir(或 Phoenix Framework)中是否有类似的东西?
String.strip/1 会将您的 3 个示例转换为 ""
,您可以与之进行比较。
iex(4)> String.strip("\n") == ""
true
iex(5)> String.strip("") == ""
true
iex(6)> String.strip(" ") == ""
true
从 Elixir 1.3.0 开始,String.trim/1 似乎可以解决问题。
strip
仍然有效,但已被软弃用 in the 1.3.0 release and it isn't listed in the String docs。
我发布了一个小型库来为任何数据类型正确执行此操作。它尽可能实现与 Elixir 中的 Rails' blank?
方法相同的行为。
图书馆在这里:https://github.com/samphilipd/blankable
要安装,请将 blankable 添加到 mix.exs 中的依赖项列表中:
def deps do
[{:blankable, "~> 0.0.1"}]
end
为什么不直接使用模式匹配
iex> a = ""
""
iex> b = "b"
"b"
iex> ^b = "b"
"b"
iex> ^a = "your String"
** (MatchError) no match of right hand side value: ""
iex> ^a = ""
""
或者更好的是检查它的字节大小
iex> if byte_size("") == 0 do true else false end
true
iex> if byte_size("a") == 0 do true else false end
false
我今天也有同样的问题。我最终定义了这些函数:
defmodule Hello do
def is_blank(nil), do: true
def is_blank(val) when val == %{}, do: true
def is_blank(val) when val == [], do: true
def is_blank(val) when is_binary(val), do: String.trim(val) == ""
def is_blank(val), do: false
end
import Hello
is_blank nil
is_blank []
is_blank %{}
is_blank ""
is_blank ["A"]
is_blank %{a: "A"}
is_blank "A"
这在大多数情况下对我有用,并且与 Ruby 中的 is_blank?
非常相似。
def is_blank?(data), do: (is_nil(data) || Regex.match?(~r/\A\s*\z/, data))
我的意思是,如果字符串为空或仅包含空格,则该字符串为空白。
例如""
、" "
、"\n"
都是空白。
在Rails中,我们有.blank?
方法。
Elixir(或 Phoenix Framework)中是否有类似的东西?
String.strip/1 会将您的 3 个示例转换为 ""
,您可以与之进行比较。
iex(4)> String.strip("\n") == ""
true
iex(5)> String.strip("") == ""
true
iex(6)> String.strip(" ") == ""
true
String.trim/1 似乎可以解决问题。
strip
仍然有效,但已被软弃用 in the 1.3.0 release and it isn't listed in the String docs。
我发布了一个小型库来为任何数据类型正确执行此操作。它尽可能实现与 Elixir 中的 Rails' blank?
方法相同的行为。
图书馆在这里:https://github.com/samphilipd/blankable
要安装,请将 blankable 添加到 mix.exs 中的依赖项列表中:
def deps do
[{:blankable, "~> 0.0.1"}]
end
为什么不直接使用模式匹配
iex> a = ""
""
iex> b = "b"
"b"
iex> ^b = "b"
"b"
iex> ^a = "your String"
** (MatchError) no match of right hand side value: ""
iex> ^a = ""
""
或者更好的是检查它的字节大小
iex> if byte_size("") == 0 do true else false end
true
iex> if byte_size("a") == 0 do true else false end
false
我今天也有同样的问题。我最终定义了这些函数:
defmodule Hello do
def is_blank(nil), do: true
def is_blank(val) when val == %{}, do: true
def is_blank(val) when val == [], do: true
def is_blank(val) when is_binary(val), do: String.trim(val) == ""
def is_blank(val), do: false
end
import Hello
is_blank nil
is_blank []
is_blank %{}
is_blank ""
is_blank ["A"]
is_blank %{a: "A"}
is_blank "A"
这在大多数情况下对我有用,并且与 Ruby 中的 is_blank?
非常相似。
def is_blank?(data), do: (is_nil(data) || Regex.match?(~r/\A\s*\z/, data))