Why doesn't this regex work?

Hi,

I’m trying to use the Regex elixir module to split a string into substrings of 3 letters each.
To do this I’ve used ~r{[A-Z][A-Z][A-Z]}, which works.
But I know that something like ~r{[A-Z]\{3\}} should also work, but using that doesn’t seem to do anything. It just outputs the same string.

BTW, I’m using both include_captures: true and trim: true.
In case that matters.

What am I missing?

Thank you in advance :slight_smile:

It seems like you only need to escape the closing character, but not the starting one.

iex(2)> IO.inspect ~r{[A-Z]\{3\}}, structs: false
%{
  __struct__: Regex,
  opts: "",
  re_pattern: {:re_pattern, 0, 0, 0,
   <<69, 82, 67, 80, 110, 0, 0, 0, 0, 0, 0, 0, 65, 0, 0, 0, 255, 255, 255, 255,
     255, 255, 255, 255, 0, 0, 125, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0,
     0, ...>>},
  re_version: {"8.41 2017-07-05", :little},
  source: "[A-Z]\\{3}"
}
~r/[A-Z]\{3}/
iex(4)> IO.inspect ~r([A-Z]{3}), structs: false
%{
  __struct__: Regex,
  opts: "",
  re_pattern: {:re_pattern, 0, 0, 0,
   <<69, 82, 67, 80, 109, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 255, 255, 255, 255,
     255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0,
     ...>>},
  re_version: {"8.41 2017-07-05", :little},
  source: "[A-Z]{3}"
}
~r/[A-Z]{3}/
iex(5)> IO.inspect ~r{[A-Z]{3\}}, structs: false
%{
  __struct__: Regex,
  opts: "",
  re_pattern: {:re_pattern, 0, 0, 0,
   <<69, 82, 67, 80, 109, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 255, 255, 255, 255,
     255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0,
     ...>>},
  re_version: {"8.41 2017-07-05", :little},
  source: "[A-Z]{3}"
}
~r/[A-Z]{3}/
3 Likes

FYI sigils can use 8 different delimiters (see docs). So in this case, it might be better to use something like ~r/[A-Z]{3}/ to make it more readable since you won’t need to escape.

3 Likes