fireproofsocks

fireproofsocks

When is \s not a \s? Can someone explain Regex patterns?

A \s inside a string represents a space, i.e. " ". In other words:

iex> " " === "\s"
true
iex> "this is a string" === "this\sis\sa\sstring"
true

However, inside a regular expression, the \s takes on a different meaning: it is shorthand for “whitespace character”, so it can match on tabs, newlines, and more. Here it can replace all of them in one swoop:

iex> str = "\tsome\nthing   with\f\nspaces\s\s"
"\tsome\nthing   with\f\nspaces  "
iex> Regex.replace(~r/\s+/, str, "-")
"-some-thing-with-spaces-"

Whereas if you just want to replace literal spaces, you have to explicitly use a space character and NOT \s:

iex> Regex.replace(~r/ +/, str, "-")
"\tsome\nthing-with\f\nspaces-"

By contrast, you can replace specific characters like tabs by referencing them literally:

iex> Regex.replace(~r/\t+/, str, "-")
"-some\nthing   with\f\nspaces  "

Can someone explain why this is the case? I just had this realization that \s is not a \s and I wanted to put the thought out to the community in a coherent post.

Related, I finally understand how the u unicode flag can affect the output. E.g. referencing a chart of whitespace characters, we can come up with a string that uses unicode whitespace characters:

iex> str = "Unicode\u00A0spaces\u2006"
"Unicode spaces "
iex> Regex.replace(~r/\s+/, str, "-")
"Unicode spaces "  # <-- spaces not matched!
iex> Regex.replace(~r/\s+/u, str, "-")
"Unicode-spaces-"  #< -- the u flag causes the spaces to be matched!

Most Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

How the \s is interpreted depends on the surrounding syntax, which all sigils have an opportunity to change. For example:

iex(3)> IO.puts "\s"
 
:ok
iex(4)> IO.puts ~S(\s)
\s
:ok
iex(5)> 

It isn’t so much about regular expressions as it is about sigils being allowed to interpret their inner contents.

Nicd

Nicd

You are mixing two different syntaxes. Strings and regular expressions are different things and have different escapes.

Strings/sigils in Elixir have these escapes: https://elixir-lang.org/getting-started/sigils.html#interpolation-and-escaping-in-string-sigils

Elixir’s regular expression library on the other hand is based on PCRE and it has the PCRE escapes, that are described here: re — OTP 29.0.2 (stdlib 8.0.1)

Both systems are different and any commonalities in their escapes are coincidental and a result of people gravitating towards the escapes that are already in common use when designing systems. So \s in a string is different from \s in a regex.

Note also that in strings/sigils, escapes are used to represent single, specific characters. In a regex escapes can be used to match certain ranges of characters (1..n). So they can’t be mapped to each other because they are for different things.

Where Next?

Popular in Questions Top

New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 42920 311
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement