【问题标题】:Elixir - Split a string so it doesn't return empty strings in the list?Elixir - 拆分一个字符串,使其不会在列表中返回空字符串?
【发布时间】:2016-05-11 07:50:18
【问题描述】:

我在正则表达式上拆分字符串。结果数组包含正则表达式匹配的空字符串。我不想要那些。例如,

iex(1)> String.split("Hello world. How are you?", ~r/\W/)
["Hello", "world", "", "How", "are", "you", ""]

如何拆分字符串,使其不在列表中返回空字符串?

【问题讨论】:

    标签: elixir


    【解决方案1】:

    the String.split docs中所述,

    只有当 trim 选项设置为 true(默认为 false)时,才会从结果中删除空字符串。

    因此,您需要在调用 String.split 时将其作为一个选项添加:

    String.split("Hello world. How are you?", ~r/\W/, trim: true)
    ["Hello", "world", "How", "are", "you"]
    

    【讨论】:

      猜你喜欢
      • 2011-11-15
      • 2019-12-23
      • 2014-12-30
      • 2021-11-16
      • 2018-06-01
      • 2018-08-15
      • 1970-01-01
      • 2012-05-12
      • 2013-03-08
      相关资源
      最近更新 更多