davdomin
davdomin

Reputation: 1219

How to extract a substring depending on a specified char using Groovy

I need to extract part of the name of a folder. I have this code for each of the folders

import groovy.io.FileType
def dirs = []
def currentDir = new File('c:\\CompilationStaging')
currentDir.eachFile FileType.DIRECTORIES, {
    dirs.add( 'C:\\CompilationStaging\\'+it.name)
    println( it.name)
}
dirs.sort() 
def list = dirs.reverse()

This gets me a list of folders, in a specific format:

I need to get for each it.name only the last part of the name (value1, value2, value3) thanks....

Upvotes: 0

Views: 1052

Answers (3)

Alfergon
Alfergon

Reputation: 5909

If last part will always be after a '_' character then use the [] operator as with lists (which is getAt() method):

it.name[it.name.lastIndexOf('_')+1..-1]

Or using regex

def regex = /.*(Value\d+$)/
def matcher = (it.name =~ regex)
println matcher[0][1]

Upvotes: 2

dmahapatro
dmahapatro

Reputation: 50245

Also try

it.name.reverse().takeWhile{it != /_/}.reverse()

Upvotes: 2

tim_yates
tim_yates

Reputation: 171074

Try

println( it.name.split( '_' )[ -1 ].toLowerCase() )

Upvotes: 2

Related Questions