Elixir Regex: How to put an underscore between a letter and a number?

paugramming

Pau Riosa

Posted on April 5, 2022

Elixir Regex: How to put an underscore between a letter and a number?

Intro

Today I've been struggling on transforming a camelCase word combined with a number to become a snake_case atom

"helloWorld30" -> :hello_world_30
Enter fullscreen mode Exit fullscreen mode

I tried using Macro.underscore/1 before and found out that I should not use it to manipulate strings to add underscore.

...Do not use it as a general mechanism for underscoring strings as it does not support Unicode or characters that are not valid in Elixir identifiers.

elixir docs

That's why I used Inflex: An Elixir library for handling word inflections

iex) "helloWorld30" 
|> Inflex.underscore()

iex) "hello_world30"
Enter fullscreen mode Exit fullscreen mode

Someone Helped Me Please!

But still using Inflex alone cannot show the output that I want.

Luckily I asked to the community and thank God someone helped me.

Shout out to Karl Seguin 🚀.

He come up on suggesting using RegEx module.

Here is the RegEx that he gave.

iex) Regex.replace(~r/([A-Za-z])(\d)/, "Hello World9000", "\\1_\\2") 

iex) "Hello World_9000"
Enter fullscreen mode Exit fullscreen mode

My Own Version

With another version using String module.


iex) "helloWorld30    
|> String.replace(~r/(\D)(\d)/, "\\1_\\2")

iex) "helloWorld_30"

Enter fullscreen mode Exit fullscreen mode

Overall output

To transform a camelCase word together with a number to become a snake_case atom:

iex) "helloWorld30" 
|> Inflex.underscore() 
|> String.replace(~r/(\D)(\d)/, "\\1_\\2")
|> String.to_atom()


iex) "hello_world_30"
Enter fullscreen mode Exit fullscreen mode

Happy coding!

💖 💪 🙅 🚩
paugramming
Pau Riosa

Posted on April 5, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related