Search code examples
elixirphoenix-framework

How to extract all substrings with regex pattern matching in elixir


String: Lorem ipsum {{dolor}} sit {{amet}}, consectetur adipisicing {{elit}},

I want to extract a list of all tags which are wrapped in {{ }} from above mentioned string and work on them i.e check db if they exist or not and than replace them as markdown link as follows.

[substring](/tag/:substring_id) 

i can replace them with

String.replace(string, ~r/\{\{.+?\}\}/, "new substring")

but this doesn't help me because i can't work on substrings i.e check the db.

i didn't find any String.scan or String.find type of functions which returns substrings as a list. if you know how to do it than please let me know.

Thanks in advance for your effort and time :)


Solution

  • You can use Regex.replace/4 with a function as replacement:

    db = %{"dolor" => 1, "elit" => 2}
    
    string = "Lorem ipsum {{dolor}} sit {{amet}}, consectetur adipisicing {{elit}},"
    
    Regex.replace(~r/{{(.+?)}}/, string, fn whole, tag ->
      if id = db[tag] do
        "[#{tag}](/tag/#{id})"
      else
        whole
      end
    end) |> IO.puts
    

    Output:

    Lorem ipsum [dolor](/tag/1) sit {{amet}}, consectetur adipisicing [elit](/tag/2),