Ajwah
Regex Multi Capture Groups
Regex Question: Given following string: "default via 10.141.23.1 dev eth0 \n10.141.23.0/24 dev eth0 proto kernel scope link src 10.141.23.235 \n169.254.169.254 dev eth0 \n172.17.0.0/16 dev docker0 proto kernel scope link src 172.17.0.1 \n"
I want to retrieve the following result: %{"default" => "10.141.23.1", "docker0" => "172.17.0.1"}
I can retrieve separately, like this: ~r/default via (?<default>\d+\.\d+\.\d+\.\d+)/ |> Regex.named_captures(str)
and ~r/dev docker0 proto kernel scope link src (?<docker0>\d+\.\d+\.\d+\.\d+)/ |> Regex.named_captures(str)
But I am not able to retrieve the desired result by combining both into one regex
e.g.
~r/default via (?<default>\d+\.\d+\.\d+\.\d+).*dev docker0 proto kernel scope link src (?<docker0>\d+\.\d+\.\d+\.\d+)/ |> Regex.named_captures(str)
returns nil
Most Liked
Qqwy
It is because by default, regular expressions treat newline characters in a special way. In your case, you’ll have to add the dotall option (sigil flag s) to ensure that the .* part between your two regular expression parts will not fail when a \n is reached:
r6 = ~r{default via (?<default>\d+\.\d+\.\d+\.\d+).+dev docker0 proto kernel scope link src (?<docker0>\d+\.\d+\.\d+\.\d+)}s
Regex.named_captures(r6, str)







