CamelCase2snake_case() Write a function to convert CamelCased text to snake_case: FunctionForHTMLManipulation becomes function_for_html_manipulation

The input text will be a single suitable identifier in many languages. It must start with an English letter, then be followed by any number of English letters or digits. No other characters (spaces, symbols, etc.) are allowed.

Each "word" within the CamelCased text will start with a capital letter unless at the beginning of the text or immediately after a digit, and be followed by zero or more letters, all of the same case. Groups of digits will be considered as separate words but pass through unchanged.

In other words, a lowercase letter followed by an uppercase letter indicates a word break. Any letter and digit next to each other indicates a word break. An uppercase letter followed by another uppercase letter and a lowercase letter indicates a word break.

...lU... => ...l_u...
...l9... => ...l_9...
...U9... => ...u_9...
...9l... => ...9_l...
...9U... => ...9_u...
...UUl... => ...u_ul...  

Both Buy24Beers and buy24beers become buy_24_beers.
MacDonaldAndObrian becomes mac_donald_and_obrian.
MACDonaldAndOBrian becomes mac_donald_and_o_brian.
Retina, 61 37 bytes

r1&gt;`[A-Z]?[a-z]+|[A-Z]+|\d+
_$&amp;
T`L`l


Try it online! (Slightly modified to run a full test suite.)

Explanation

Instead of finding word boundaries to insert underscores, we simply match each word and prepend a _. Matching words from the left is a bit annoying because of the UUl rule, but using .NET's right-to-left matching we can easily match words greedily. To avoid a leading _, we make use of Retina's limits.

r1&gt;`[A-Z]?[a-z]+|[A-Z]+|\d+
_$&amp;


The r activates right-to-left mode, the 1&gt; tells Retina to process everything except the first match (counting from left to right). Then there's four types of "words": Ulll, lll, UUU, ddd. These are easily matched with the given pattern. The substitution just writes a _ followed by the word itself.

T`L`l


This simply turns upper case into lower case to complete the transformation.