How do you embed double-quotes an Elixir string?

风流意气都作罢 提交于 2019-12-10 01:48:04

问题


I have a sting that has embedded ":

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

how can i present such a string as a value in Elixir?

for example:

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

Using ~s and ~S did not help

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)> 

回答1:


You can escape the double quotes:

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

There is a sigil_s to make this more convenient (there is also sigil_S which doesn't interpolate variables):

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

Quotes are also escaped when using multi-line strings (heredocs):

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



回答2:


The ~s or ~S sigils are the way to go, you just need a space after your equals sign:

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\">\""


来源:https://stackoverflow.com/questions/33185095/how-do-you-embed-double-quotes-an-elixir-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!