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)
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









