Regex.scan stumbles upon brackets

Hello there,

when I do Regex.scan(~r/\d+|[+\-*/()]/, "6000 / 4000"), I get an error

iex(11) > Regex.scan(~r/\d+|[+\-*/()]/, "6000 / 4000")
** (SyntaxError) iex:11:27: unexpected token: ]. The "(" at line 11 is missing terminator ")"
    (iex 1.14.5) lib/iex/evaluator.ex:292: IEx.Evaluator.parse_eval_inspect/3
    (iex 1.14.5) lib/iex/evaluator.ex:187: IEx.Evaluator.loop/1
    (iex 1.14.5) lib/iex/evaluator.ex:32: IEx.Evaluator.init/4
    (stdlib 5.2.3) proc_lib.erl:241: :proc_lib.init_p_do_apply/3
iex(11) >

At link to www.elixirregex.com, it does work and gives me the tokens I need:

[0]: 6000
[1]: /
[2]: 4000

Yesterday, I tried Elixir 1.18.4, but got the same error.

What am I doing wrong? I dont understand, why I get such deviating results.

Your help is highly appreciated!

Yours,
Volker

Try escaping the / in front of the parentheses.

2 Likes

The problem is that the / inside your regex is being treated as the closing delimeter of the ~r sigil. You can work around by choosing a different delimiter:

iex(1)> Regex.scan(~r{\d+|[+\-*/()]}, "6000 / 4000")
[["6000"], ["/"], ["4000"]]

elixirregex.com is probably not executing the code it is showing you, but running Regex.compile/2 on the regex string.

6 Likes

Thank you, adamu!

That was spot-on! I did not know about the possibility to choose a different delimiter.

1 Like

Note that the delimiters come from sigils, not regex. You can find a list of them in the Sigils docs, ironically in the regex section :slight_smile:

3 Likes