你如何在 Elixir 字符串中嵌入双引号?

How do you embed double-quotes an Elixir string?

我有一个嵌有 的刺针:

tx <iq id="wUcdTMYuYoo41" to="2348138248411@" type="set" xmlns="w:profile:picture">

如何在 Elixir 中将这样的字符串显示为值?

例如:

iex> s= "tx <iq id="wUcdTMYuYoo41" to="2348138248411@" type="set" xmlns="w:profile:picture">"

使用 ~s 和 ~S 没有帮助

iex(20)> s=~S("tx <iq id="wUcdTMYuYoo41" to="2348138248411@" type="set" xmlns="w:profile:picture">")              
** (SyntaxError) iex:20: keyword argument must be followed by space after: w:

iex(20)> s=~s("tx <iq id="wUcdTMYuYoo41" to="2348138248411@" type="set" xmlns="w:profile:picture">")
** (SyntaxError) iex:20: keyword argument must be followed by space after: w:

iex(20)> 

双引号可以转义:

s ="tx <iq id=\"wUcdTMYuYoo41\" to=\"2348138248411@\" type=\"set\" xmlns=\"w:profile:picture\">"

有一个 sigil_s to make this more convenient (there is also sigil_S 不插值变量):

s = ~s(tx <iq id="wUcdTMYuYoo41" to="2348138248411@" type="set" xmlns="w:profile:picture">)

使用多行字符串时引号也会被转义(heredocs):

"""
tx <iq id="wUcdTMYuYoo41" to="2348138248411@" type="set" xmlns="w:profile:picture">
"""

~s~S 印记是正确的选择,您只需要在等号后加上 space:

iex(1)> s = ~s("tx <iq id="wUcdTMYuYoo41" to="2348138248411@" type="set" xmlns="w:profile:picture">")
"\"tx <iq id=\"wUcdTMYuYoo41\" to=\"2348138248411@\" type=\"set\" xmlns=\"w:profile:picture\">\""

iex(2)> s = ~S("tx <iq id="wUcdTMYuYoo41" to="2348138248411@" type="set" xmlns="w:profile:picture">")
"\"tx <iq id=\"wUcdTMYuYoo41\" to=\"2348138248411@\" type=\"set\" xmlns=\"w:profile:picture\">\""