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

14

我有一个包含嵌入的"字符的字符串:

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)> 
2个回答

24

您可以通过使用转义字符来避免双引号:

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

有一个sigil_s可以使这更加方便(还有一个不插入变量的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">
"""

谢谢。当我们从File.stream!(“路径/到/文件”)中提取这样的字符串时,需要对返回的每一行都做同样的操作吗? - Charles Okwuagwu
1
使用 File.Stream 将自动转义引号。例如:iex(4)> IO.gets ">"; >""" "TEST "" "; "\"\"\" \"TEST \"\" \"\n" - Gazler
请注意,"s" 和 "S" 无法工作,请查看上面编辑问题时报告的错误。 - Charles Okwuagwu
1
你需要在 ~ 前面加上一个空格 - s = ~s(...) 而不是 s=~s(...) - Gazler

5
~s~S保留字是正确的选择,您只需要在等号后加一个空格即可:
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\">\""

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接