[英]Groovy: regex to filter out “Key:Value” pair and store in an array
I am writing a GROOVY script for a Jenkinsfile to do following: 我正在为Jenkinsfile编写GROOVY脚本,以执行以下操作:
Step-1: read the input file info_file.txt
. 步骤1:读取输入文件
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.. 步骤2:删除后缀
-A0,-B1
等后,将CHIP_DETAILS
存储在数组中。
for example: 例如:
Integer[] testArray = ["1234", "1456", "2456" , "3436" , "4467"]
Step-3: print the elements of the array sequentially. 步骤3:依序列印阵列中的元素。 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. 我编写了一个小代码来测试
CHIP_DETAILS
'是否存在于输入文件中并且可以正常工作。 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. 但是,我发现很难编写用于删除后缀(
-A0,-B1
等)并将正则表达式存储在数组中的正则表达式。 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! 在此先感谢您的帮助!
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.