Elixir 印記的插值與逃避

2023-12-16 20:46 更新
除了小寫印記,Elixir也支持用于處理轉(zhuǎn)義字符與插值的大寫印記.雖然~s~S都會(huì)返回字符串,但前者支持轉(zhuǎn)義代碼和插值,而后者不支持:
iex> ~s(String with escape codes \x26 #{"inter" <> "polation"})
"String with escape codes & interpolation"
iex> ~S(String without escape codes \x26 without #{interpolation})
"String without escape codes \\x26 without \#{interpolation}"

下列轉(zhuǎn)義代碼可以用于字符串和字符列表:

\" – 雙引號
\' – 單引號
\\ – 單反斜杠
\a – 響鈴/警告
\b – 推格
\d - 刪除
\e - 退出
\f - 換頁符
\n – 換行符
\r – 回車
\s – 空格
\t – 制表符
\v – 垂直制表符
\0 - 空字節(jié)
\xDD - 以16進(jìn)制表示單字節(jié) (例如 \x13)
\uDDDD and \u{D...} - 以16進(jìn)制表示Unicode代碼點(diǎn) (例如 \u{1F600})

印記也支持大段注釋,以三個(gè)單引號或雙引號分隔:

iex> ~s"""
...> this is
...> a heredoc string
...> """

大段注釋印記最常用于書寫文檔.例如,在文檔中書寫轉(zhuǎn)義字符會(huì)很麻煩,因?yàn)樾枰獙δ承┓柺褂秒p重轉(zhuǎn)義:

@doc """
Converts double-quotes to single-quotes.

## Examples

    iex> convert("\\\"foo\\\"")
    "'foo'"

"""
def convert(...)

使用?~S?,這些問題就可以避免:

@doc ~S"""
Converts double-quotes to single-quotes.

## Examples

    iex> convert("\"foo\"")
    "'foo'"

"""
def convert(...)


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號