我正在尝试在Jenkins的常规DSL中拆分URL http://localhost:8081/artifactory/api/storage/myrepo/sub1/file.zip。它是单行字符串。但是下面的代码不起作用
String[] arr= string_var.split('/');
String[] arr=string_var.split('\\/');
它不拆分它,并以arr [0]返回自身。 我不确定这是否是错误。请告诉我是否有其他方法可以从URL字符串中获取“ sub1”。
答案 0 :(得分:1)
确定要正确执行DSL脚本吗?常规代码看起来还可以。 尝试跳过声明类型
def url_str = 'http://localhost:8081/artifactory/api/storage/myrepo/sub1/file.zip'
def sub = url_str.split('/')[-2]
println(sub)
一行:
println('http://localhost:8081/artifactory/api/storage/myrepo/sub1/file.zip'.split('/')[-2])
不拆分,索引:
def url_str = 'http://localhost:8081/artifactory/api/storage/myrepo/sub1/file.zip'
int[] indexes = url_str.findIndexValues {it == "/"}
println url_str.substring(indexes[-2] + 1, indexes[-1])
答案 1 :(得分:0)
尝试将您的代码包含在DSL语言的“脚本”标签中,如以下代码所示:
pipeline {
agent any
stages {
stage('Test') {
steps {
script {
def string_var = "http://localhost:8081/artifactory/api/storage/myrepo/sub1/file.zip"
String[] arr= string_var.split('/');
println "${arr[0]}"
}
}
}
}
}
执行上面的代码,我在控制台上得到以下结果:
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
http:
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
因此,提供预期的“ http:”字符串
获取字符串'sub1'(正则表达式)的另一种Groovy方法:
String s = "http://localhost:8081/artifactory/api/storage/myrepo/sub1/file.zip"
def match = s =~ /(sub1)/
if (match.size() > 0) { // If url 's' contains the expected string 'sub1'
println match[0][1]
// Or do something with the match
}