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 exerciseMore exercises in Extraction and cleanup
- Log lines: level and messageFree
- key=value pairsFree
- The third CSV fieldFree
- HashtagsFree
- Host names from URLsFree
- A query string parameterFree
- File extensionsFree
- Trim whitespaceFree
- Collapse repeated spacesFree
- Reformat MM/DD/YYYY as YYYY-MM-DDFree
- Swap Last, First to First LastFree
- Strip HTML tagsFree
- Keep only the digitsFree
- CSV fields with quotesFree
- Normalize phone numbersFree
- Link text inside <a> tagsFree
- Web server access logFree