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.

See &Regex.compile/2.

2 Likes

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

5 Likes

@NobbZ: Yeah, but this method returns what’s wromg with regex, so I think that it’s more safe. Regex module has also method to escape special characters.

1 Like

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:

3 Likes