【问题标题】:Pattern match on substring in ElixirElixir中子字符串的模式匹配
【发布时间】:2018-01-12 17:16:12
【问题描述】:

如何在通过分号的任一侧将返回 true 的字符串上进行模式匹配?换句话说,有没有一种简单的方法来模式匹配它包含的子字符串?

@matched_string "x-wat"

def match(@matched_string), do: true

match("x-wat") # true
match("x-wat; s-wat") # true
match("s-wat; x-wat") # true
match("s-wat") # false
match("x-wat-y") #false

【问题讨论】:

  • 能否保证不匹配的字符串和匹配的字符串大小相同?

标签: elixir


【解决方案1】:

不,这不能通过模式匹配来完成。您可以匹配字符串的前缀,或者如果您知道字符串开头每个部分的长度,您可以指定它们的大小并匹配例如<<_::size(4), @matched_string, _::binary>>,但您通常不能匹配任何任意子字符串。在这种情况下,您可以改为拆分 ;,修剪字符串,并检查它是否包含 "x-wat"

def match(string) do
  string |> String.split(";") |> Enum.map(&String.trim/1) |> Enum.member?(string)
end

【讨论】:

    【解决方案2】:

    由于@Dogbert 解释的原因,您不能这样做,但是有很多方法可以检查子字符串。

    如果你没有限制,你可以这样做

    iex> "s-wat; x-wat" =~ "x-wat"
    true
    
    iex> String.contains? "s-wat; x-wat", "x-wat"
    true
    

    但是你有一些限制,所以你可以发挥创造力。我将在现有答案之上添加另一个示例:

    一个使用Regex的例子:

    @matched_string "x-wat"
    
    def match?(string) do
      ~r/^(.+; )?(#{@matched_string})(; [^\s]+)?$/ |> Regex.match?(string)
    end
    

    验证:

    iex(1)> import Regex
    Regex
    
    iex(2)> matched_string = "x-wat"
    "x-wat"
    
    iex(3)> r = ~r/^(.+; )?(#{matched_string})(; [^\s]+)?$/
    ~r/^(.+; )?(x-wat)(; [^\s]+)?$/
    
    iex(4)> match?(r, "x-wat")
    true
    
    iex(5)> match?(r, "x-wat; s-wat")
    true
    
    iex(6)> match?(r, "s-wat; x-wat")
    true
    
    iex(7)> match?(r, "s-wat")
    false
    
    iex(8)> match?(r, "x-wat-y")
    false
    

    【讨论】:

      猜你喜欢
      • 2017-12-03
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 2021-03-07
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多