Extract Maven Dependency Version as Property

Problem: You got a lot of <version> tags in your Maven pom.xml that you want to centralize in <properties> section.

Solution: Use an editor with greedy RegEx functionality like Notepad++ 5.9+ to find and replace.

  • Find: (<dependency>\s+<groupId>)(.+)(</groupId>\s+<artifactId>)(.+)(</artifactId>\s+<version>)([^\$]+?)(</version>[\s\S]*?\s+</dependency>)
  • Replace: \1\2\3\4\5${\4.version}\7\n<\4.version>\6</\4.version>

This puts property in line under the dependency to be cut and pasted. The property is named after <artifactId> tag followed by .version, e. g. <example.version>. To clarify look at following example:

<dependency>
      <groupId>org.example.one</groupId>
      <artifactId>example1</artifactId>
      <version>1.2.3</version>
</dependency>

becomes

<dependency>
      <groupId>org.example.one</groupId>
      <artifactId>example1</artifactId>
      <version>${example1.version}</version>
</dependency>
<example1.version>1.2.3</example1.version>

Some more examples could be found here: RegEx101 example.

If you want to summon a little more magic use the following to directly paste <example.version> property into <properties> section.

  • Find: (<properties>)([\s\S]+?)(<dependency>\s+<groupId>)(.+)(</groupId>\s+<artifactId>)(.+)(</artifactId>\s+<version>)([^\$]+?)(</version>[\s\S]*?\s+</dependency>)
  • Replace: \1\n<\6.version>\8</\6.version>\2\3\4\5\6\7${\6.version}\9

Improvement: As you can see it’s not necessary to use that much capturing groups in RegEx pattern. You could of course join them, but this way it’s a little easier to customize resulting property.

Categories: Stuff