简体   繁体   中英

Is it possible to escape a space in a word list sigil?

I'm trying to create an atom list with all the provinces of Argentina. Since some of the are composed of multiple words, I need to escape the whitespace.

~w[
  Buenos\sAires
  Capital\sfederal Catamarca Chaco Chubut Corrientes Córdoba
  Entre\sRíos Formosa Jujuy La\sPampa La\sRioja Mendoza Misiones Neuquén
  Río\sNegro Salta San\sJuan San\ Luis Santa\sCruz Santa\sFe
  Santiago\sdel\sEstero Tierra\sdel\sFuego Tucumán
]a

I've tried using sigil_w and sigil_W , with the classic escaping sequences \\ and \\s , but it does not work.

(26 provinces - 1) * (2 quotes (") + 1 comma (,) + 1 space for readability(" ")) - 25 spaces I would use with the sigil form = 75 characters I could save

I know I can achieve this using a custom sigil:

defmodule MySigil do
  def sigil_X(string, [])  do
   string
   |> String.split(~r/\s/)
   |> Enum.map(&String.replace(&1, "\\s", " "))
  end
end

import MySigil
~X[Buenos\sAires La\sPlata]
["Buenos Aires", "La Plata"]

... but is there less "homemade" approach?

No, this is not possible. sigil_w and sigil_W both call the private split_words method in the Kernel module, which uses String.split to split the string which will always split on any whitespace.

While it's not possible without hacks, there is a kludge around. Copy-paste the code below into your iex and execute it:

~w|a b c|
#⇒ ["a b", "c"]

[ NB unfortunately, SO has the original symbol converted to normal space, hence copy-paste won't work out of the box] I can hear your “wut?” :)

This is achieved with a non-breakable space . If you are fine with this, just use nbsp and you are all set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM