Regexdrill

Level 4: Extraction and cleanup Exercise 62 of 88 Free

Split camelCase with underscores

A regex exercise from Regexdrill. Solve it with a pattern box with live highlighting in your browser, checked against hidden test strings, and it is checked the moment you submit.

The task

Insert an underscore at every place where a lowercase letter or a digit is directly followed by a capital letter, so userId becomes user_Id. Leave the letters themselves unchanged.

What this exercise teaches

([a-z0-9])([A-Z]) finds each boundary between two words of a camelCase name, and $1_$2 puts the two captured characters back around the underscore. A run of capitals such as URL has no lowercase letter inside it, so it stays together. Lowercasing the result is a job for the programming language, not for the replacement text.

A hint if you get stuck

Capture the lowercase letter or digit in group 1 and the capital in group 2, then write them back with an underscore in between: $1_$2. Use the g flag.

Try it now, free, no account needed

Every exercise on Regexdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.

Open this exercise

More exercises in Extraction and cleanup