Valentin T.
Valentin T.

Reputation: 529

Elixir regex groups and ?-mark

I'm trying to use the following regex

~r/(?<cmd>.*)(:(?<args>.*))?/

to get the following behaviour

"COMMAND:ARGS" => %{cmd: "COMMAND", args: "ARGS"}
"COMMAND" => %{cmd: "COMMAND", args: nil}

But all I get is

iex(66)> Regex.named_captures(~r/(?<cmd>.*)(:(?<args>.*))?/, "COMMAND:ARG")
%{"args" => "", "cmd" => "COMMAND:ARG"}
iex(67)> Regex.named_captures(~r/(?<cmd>.*)(:(?<args>.*))?/, "COMMAND")       
%{"args" => "", "cmd" => "COMMAND"}

What am I doing wrong?

Upvotes: 1

Views: 298

Answers (1)

ctwheels
ctwheels

Reputation: 22837

See regex in use here

(?<cmd>[^:]+)(?::(?<args>.*))?
(?<cmd>[^:\n]+)(?::(?<args>.*))?   # for multiline content
  • (?<cmd>[^:\n]+) Capture any character except : or \n (in the second version) into capture group named cmd
  • (?::(?<args>.*))? Optionally match the following
    • : Match this literally
    • (?<args>.*) Capture the rest of the line into capture group named args

Results:

Match 1
    Full match      0-12    `COMMAND:ARGS`
    Group `cmd`     0-7     `COMMAND`
    Group `args`    8-12    `ARGS`
Match 2
    Full match      13-20   `COMMAND`
    Group `cmd`     13-20   `COMMAND`

Upvotes: 2

Related Questions