Tip of the day: using capture groups and back references to search and replace in IntelliJ
Using capture groups and back references to search and replace in IntelliJ
Yesterday, I wanted to fix a small issue across a codebase: for some reasons, previous developers thought it was a good idea to use a lowercase ‘l’ (L) in all of the unit tests in order to define Long values.
Here’s an example:
calculator.add(1l);
The issue with this is that it is unreadable and it is tiresome have to guess whether it is 1 or 11. It’s not a big issue, but it annoyed me enough to want to quickly fix it in the whole codebase.
Luckily, I could make use of IntelliJ’s search & replace functionality. To find all the occurrences, I’ve used the following regular expression:
(\d)(l)
With it, I simply look for all numbers directly followed by a ‘l’ (L).
Finding the occurrences was quite easy and as a matter of fact, replacing is also very easy to do, thanks to the capture group back-reference support of IntelliJ.
Here’s the replacement string that I’ve used to fix it everywhere easily:
$1L
The $1
refers to the first capturing group of the search regular expression. This basically tells IntelliJ to use the value of the first capturing group (which would be “1” in my example above) and replace the rest with “L”.
Problem solved! :)
You can learn more about this feature here: https://www.jetbrains.com/help/idea/tutorial-finding-and-replacing-text-using-regular-expressions.html#capture_groups_and_backreference
That's it for today! ✨
About Sébastien
I am Sébastien Dubois. You can follow me on X 🐦 and on BlueSky 🦋.
I am an author, founder, and coach. I write books and articles about Knowledge Work, Personal Knowledge Management, Note-taking, Lifelong Learning, Personal Organization, and Zen Productivity. I also craft lovely digital products . You can learn more about my projects here.
If you want to follow my work, then become a member.
Ready to get to the next level?
To embark on your Knowledge Management journey, consider investing in resources that will equip you with the tools and strategies you need. Check out the Obsidian Starter Kit and the accompanying video course. It will give you a rock-solid starting point for your note-taking and Knowledge Management efforts.
If you want to take a more holistic approach, then the Knowledge Worker Kit is for you. It covers PKM, but expands into productivity, personal organization, project/task management, and more:
If you are in a hurry, then do not hesitate to book a coaching session with me: