Groovy: regex to filter out “Key:Value” pair and store in an array

牧云@^-^@ 提交于 2019-12-12 04:34:23

问题


I am writing a GROOVY script for a Jenkinsfile to do following:

Step-1: read the input file info_file.txt. Contents of info file are as under:

sh> cat info_file.txt
CHIP_DETAILS:1234-A0;1456-B1;2456-B0;3436-D0;4467-C0

Step-2: Store the CHIP_DETAILS in an array after removing the suffix -A0,-B1 etc..

for example:

Integer[] testArray = ["1234", "1456", "2456" , "3436" , "4467"]

Step-3: print the elements of the array sequentially. For example:

testArray.each {
println "chip num is ${it}"
}

I have written a small code to test if the CHIP_DETAILS 'key' is present in the input file and it is working. However i'm finding it difficult to write the regex for removing the suffix (-A0,-B1 etc..) and storing the corresponding value in an array. the code is as under:

stage('Read_Params') 
        { 
            steps 
            {
                script
                {
                    println ("Let's validate and see whether the "Key:Value" is present in the info_file.txt\n");
                    if ( new File("$JobPath/Inputparams.txt").text?.contains("CHIPS_DETAILS"))
                    {
                       println ("INFO: "Key:Value" is present in the info_file.txt \n");
                      >>>>> proceed with Step-1, Step-2 and Step-3... <<<<< 
                    }
                    else 
                    {
                       println ("WARN: "Key:Value" is NOT present in the info_file.txt  \n");
                       exit 0;
                    }
                }
            }   
        }

Thanks in advance for help!


回答1:


You could try something like the following:

def chipDetails = 'CHIP_DETAILS:1234-A0;1456-B1;2456-B0;3436-D0;4467-C0'

def testArray = ( chipDetails =~ /(?<=^|[:;])\d*(?=[-])/)​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
assert​ '1234' == testArray[0]
assert '1456' == testArray[1]
assert '2456' == testArray[2]
assert '3436' == testArray[3]
assert '4467' == testArray[4]​

The regular expression ensures the number you're trying to capture is either at the start of a line or prefixed with : or ; and suffixed with -

There can be any amount of digits between the delimiters.

Iterate over the results like:

testArray.each{
    println it
}​


来源:https://stackoverflow.com/questions/44158849/groovy-regex-to-filter-out-keyvalue-pair-and-store-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!