codecamp

Elixir 印记的插值与逃避

除了小写印记,Elixir也支持用于处理转义字符与插值的大写印记.虽然~s~S都会返回字符串,但前者支持转义代码和插值,而后者不支持:
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}"

下列转义代码可以用于字符串和字符列表:

\" – 双引号
\' – 单引号
\\ – 单反斜杠
\a – 响铃/警告
\b – 推格
\d - 删除
\e - 退出
\f - 换页符
\n – 换行符
\r – 回车
\s – 空格
\t – 制表符
\v – 垂直制表符
\0 - 空字节
\xDD - 以16进制表示单字节 (例如 \x13)
\uDDDD and \u{D...} - 以16进制表示Unicode代码点 (例如 \u{1F600})

印记也支持大段注释,以三个单引号或双引号分隔:

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

大段注释印记最常用于书写文档.例如,在文档中书写转义字符会很麻烦,因为需要对某些符号使用双重转义:

@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(...)


Elixir 单词列表
Elixir 自定义印记
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

Elixir 基本操作符

Elixir 二进制,字符串和字符列表

Elixir 类型规格与行为

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }