Mark is a graph advocate and field engineer for Neo Technology, the company behind the Neo4j graph database. As a field engineer, Mark helps customers embrace graph data and Neo4j building sophisticated solutions to challenging data problems. When he's not with customers Mark is a developer on Neo4j and writes his experiences of being a graphista on a popular blog at http://markhneedham.com/blog. He tweets at @markhneedham. Mark is a DZone MVB and is not an employee of DZone and has posted 553 posts at DZone. You can read more from them at their website. View Full User Profile

Find/Replace Using Regular Expressions With Capture Groups in IntelliJ

04.05.2012
| 5162 views |
  • submit to reddit

Everyone now and then we end up having to write a bunch of mapping code and I quite like using IntelliJ’s ‘Replace’ option to do it but always end up spending about 5 minutes trying to remember how to do capture groups so I thought I’d write it down this time.

Given the following text in our file:

val mark = 0
val dave = 0
val john = 0
val alex = 0

Let’s say we wanted to prefix each of those names with ‘cool’ and had decided not to use Column mode for whatever reason.

One way of doing that is to capture the names and then replace each of them with ‘cool’ appended on the beginning:

A (very hacky) find regex could be this:

\s([a-zA-Z]+)\s=

Where we capture all the letters in the variable name inside a group and then build our replacement string like so:

 cool$1 =

I always expect the capture group replacement syntax to be ‘\1′, ‘\2′ and so on but it actually uses a ‘$’ instead. Hopefully now I shall remember!

Published at DZone with permission of Mark Needham, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)