opticyclic
opticyclic

Reputation: 8126

Parse Maven Filename

How can I parse a maven filename into the artifact and and version?

The filenames look like this:

test-file-12.2.2-SNAPSHOT.jar
test-lookup-1.0.16.jar 

I need to get

test-file
12.2.2-SNAPSHOT
test-lookup
1.0.16

So the artifactId is the text before the first instance of a dash and a number and the version is the text after the first instance of a number up to .jar.

I could probably do it with split and several loops and checks but it feels like there should be a simpler way.

EDIT:

Actually, the regex wasn't as complicated as I thought!

   new File("test").eachFile() { file ->
    String fileName = file.name[0..file.name.lastIndexOf('.') - 1]
    //Split at the first instance of a dash and a number
    def split = fileName.split("-[\\d]")
    String artifactId = split[0]
    String version = fileName.substring(artifactId.length() + 1, fileName.length())

    println(artifactId)
    println(version)
  }

EDIT2: Hmm. It fails on examples such as this:

http://mvnrepository.com/artifact/org.xhtmlrenderer/core-renderer/R8
core-renderer-R8.jar

Upvotes: 1

Views: 1163

Answers (1)

user557597
user557597

Reputation:

Basically its just this ^(.+?)-(\d.*?)\.jar$
used in multi-line mode if there is more than one line.

 ^ 
 ( .+? )
 -
 ( \d .*? )
 \. jar
 $ 

Output:

 **  Grp 0 -  ( pos 0 , len 29 ) 
test-file-12.2.2-SNAPSHOT.jar  
 **  Grp 1 -  ( pos 0 , len 9 ) 
test-file  
 **  Grp 2 -  ( pos 10 , len 15 ) 
12.2.2-SNAPSHOT  

--------------------------

 **  Grp 0 -  ( pos 31 , len 22 ) 
test-lookup-1.0.16.jar  
 **  Grp 1 -  ( pos 31 , len 11 ) 
test-lookup  
 **  Grp 2 -  ( pos 43 , len 6 ) 
1.0.16  

Upvotes: 2

Related Questions