sashang
Interpolating regex expressions
How do I interpolate a regex inside another regex. Not sure if interpolate is the right word so here’s an example:
r = ~r/something/
r1 = ~r/prefix:®*/
so r in r1 is not meant to be literally interpreted as ‘r’ but rather the contents of the regex refereced by r.
Marked As Solved
Eiji
See &Regex.compile/2.
Also Liked
NobbZ
No need to do a Regex.compile/2, one can still use Sigils:
iex(1)> r = "foo"
"foo"
iex(2)> re = ~r/#{r}/
~r/foo/
This way one doesn’t need to remember escaping some Regex stuff which one had to do when using Regex.compile/2. Also it doesn’t read that clunky in the source 
NobbZ
Yeah. I missed the fact that Regex.compile/2 returns a tuple which indicates correctness of the regex while using the small-r sigil is like using a banged version which might crash.
Therefore let me summarize, that one can choose among different possibilities to achieve what was asked for, depending on ones usecase:
-
Regex.compile/2if one wants to control what happens if an invalid RegEx is created -
~r//with String interpolation (#{varname}) if it is OK if the process dies on an invalid RegEx







