【问题标题】:What does "?\s" mean in Elixir?Elixir 中的 "?\s" 是什么意思?
【发布时间】:2020-06-06 01:36:09
【问题描述】:

在涵盖 comprehensions 的 Elixir 文档中,我遇到了以下示例:

iex> for <<c <- " hello world ">>, c != ?\s, into: "", do: <<c>>
"helloworld"

我现在有点理解整个表达式,但我无法弄清楚“?\ s”是什么意思。 我知道它以某种方式匹配并因此过滤掉了空格,但这就是我的理解结束的地方。

编辑:我现在发现它解析为 32,这是一个空格的字符代码,但我仍然不知道为什么。

【问题讨论】:

    标签: string char elixir


    【解决方案1】:

    具有用美元符号表示的字符文字。

    Erlang/OTP 22 [erts-10.6.1] [...]
    
    Eshell V10.6.1  (abort with ^G)
    1> $\s == 32.
    %%⇒ true
    

    具有与 code documentation 完全相同的 char 文字的方式与 erlang char 文字相同:

    这正是 Erlang 对 Erlang 字符文字 ($a) 所做的。


    基本上,?\s 完全相同(问号后跟一个空格。)

    #               ⇓ space here
    iex|1 ▶ ?\s == ? 
    warning: found ? followed by code point 0x20 (space), please use ?\s instead
    

    ?\s 没有什么特别之处,如您所见:

    for <<c <- " hello world ">>, c != ?o, into: "", do: <<c>> 
    #⇒ " hell wrld "
    

    另外, 也使用?c 符号表示字符文字:

    main> ?\s == ' '
    #⇒ true
    

    【讨论】:

      【解决方案2】:

      ? 是一个文字,它为您提供以下字符的代码点 (https://elixir-lang.org/getting-started/binaries-strings-and-char-lists.html#utf-8-and-unicode)。对于不能按字面表达的字符(空格只是其中之一,但还有更多:制表符、回车符、...),应使用转义序列。所以?\s 给你一个空间代码点:

      iex> ?\s
      32
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-15
        • 1970-01-01
        • 2022-06-10
        • 2011-09-27
        • 2011-06-25
        • 1970-01-01
        • 2018-05-02
        相关资源
        最近更新 更多