Complex Character Replacement

This lesson covers the use case of complex character replacement for regular expressions.

We'll cover the following

We’ve done enough pattern matching for the day, haven’t we? Let’s look at regular expressions from another angle. As you know, capturing groups allow you to perform interesting replacement operations with different patterns. In this section, we’re going to show you one example of this.

Camel case to serpent case

Think about when you’re writing code and suddenly realize you have to refactor a section of your code, not because what you wrote is wrong but because of the way you wrote it. For instance, realizing you were using camel case when you should’ve used serpent case (i.e., writingLikeThis vs. writing_like_this). Changing three variable names like this is not a problem, but going through several hundred lines of code to fix this can be a pain if you do it manually. Thankfully, regular expressions can help solve this in less time.

Going from camel case to serpent case for a single string is easy. There is no context. All you need to do is search for a lowercase letter, followed by an uppercase one, capture them into different groups, and then replace them with a “_” in the middle, like this:

Get hands-on with 1200+ tech skills courses.