3

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 :)

1
  • Is the string constant except for the portion in the {{}} part? I ask because if it is constant otherwise you could use pattern matching for this too. Commented Jul 11, 2016 at 0:41

2 Answers 2

5

You can use the Regex.scan/3 function if you simply want to extract the matched regex expression into a list of values.

Regex.scan(~r/\{\{.+?\}\}/, string)
#[["{{dolor}}"], ["{{amet}}"], ["{{elit}}"]]
Sign up to request clarification or add additional context in comments.

Comments

4

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),

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.