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

Transforming a camelCase word with number into snake_case atom using RegEx


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

"helloWorld30" -> :hello_world_30

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"

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"

My Own Version

With another version using String module.

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

iex) "helloWorld_30"

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"

Happy coding!