-1

I need a Groovy/Java function to search for groups in a string based on regular expression

Ex:

function("([\w-]+)-([\w.-]+)\.([\w.-]+)" ,"commons-collections-3.2.2.jar" )

should return a list ["commons-collections" , "3.2.2" , "jar"]

Python can do this by

>> import re

>> re.search("([\w-]+)-([\w.-]+)\.([\w.-]+)" ,"commons-collections-3.2.2.jar" )

>> print(result.groups()) 

output is ("commons-collections" , "3.2.2" , "jar")

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
origin
  • 120
  • 2
  • 8

1 Answers1

0

It is a simple and basic task in groovy. Any way I hope this answer will help you.

"commons-collections-3.2.2.jar".findAll(/([\w-]+)-([\w.-]+)\.([\w.-]+)/) {    
    println it 
}

This will produce the output :

[commons-collections-3.2.2.jar, commons-collections, 3.2.2, jar]

Update :

As @tim_yates mentioned in comment,

println "commons-collections-3.2.2.jar".findAll(/([\w-]+)-([\w.-]+)\.([\w.-]+)/) { it.tail() }

This provides better output than above and also more specific to the task.

Output:

[[commons-collections, 3.2.2, jar]]
Bhanuchander Udhayakumar
  • 1,581
  • 1
  • 12
  • 30
  • 1
    A better (?) solution would be: `def result = "commons-collections-3.2.2.jar".findAll(/([\w-]+)-([\w.-]+)\.([\w.-]+)/) { it.tail() }` which will return the three fields required in the question – tim_yates Feb 07 '19 at 15:21
  • @tim_yates Thanks for the suggestion. I have updated my answer accordingly. – Bhanuchander Udhayakumar Feb 08 '19 at 05:59