Regex to replace every odd and even occurence in string

So I’m struggling about regex on markdown exercise on exercism.io

Basically how to turn something like this:

"_hello_ kevin, please go to chair number _132_ and grab the plate number _4_"

into this

"<em>hello</em> kevin, please go to chair number <em>132</em> and grab the plate number <em>4</em>"

we replace every odd "_" occurence with "<em>"

we replace every even "_" occurence with "</em>"

I’ve been tinkering with String and Regex module, but none works… or, am I doing something wrong here?

Regexes might not be the way to go :slight_smile:

iex(1)> str = "_hello_ kevin, please go to chair number _132_ and grab the plate number _4_"
iex(2)> test = Regex.replace(~r/\_(.*?)\_/, str, "<em>\\g{1}</em>") 
"<em>hello</em> kevin, please go to chair number <em>132</em> and grab the plate number <em>4</em>"

This would work if you want to do it with a regex explicitly and you’re sure a “_” will always be used to only start and end a delimitation for substitution.

Many thanks for the answer,

This is the solution, but i have no idea how the "<em>\\g{1}</em>" works.

update:
now I know how it works.

https://hexdocs.pm/elixir/Regex.html#replace/4

I know I can parse the character one by one.

I just want to know if regex could handle this, and make the code simpler.