关于jenkins:无法在groovy DSL中分割字符串并且没有多行

Not able to split string in groovy DSL and there is no multi-line

我正在尝试在Jenkins的groovy DSL中拆分URL http:// localhost:8081 / artifactory / api / storage / myrepo / sub1 / file.zip。 它是单行字符串。 但是下面的代码不起作用

1
2
String[] arr= string_var.split('/');  
String[] arr=string_var.split('\\\\/');

它不会拆分它,并以arr [0]返回自身。
我不确定这是否是错误。 请告诉我是否有其他方法可以从URL字符串中获取" sub1"。


您确定正确执行DSL脚本吗? 常规代码看起来还可以。
尝试跳过声明类型

1
2
3
def url_str = 'http://localhost:8081/artifactory/api/storage/myrepo/sub1/file.zip'
def sub = url_str.split('/')[-2]
println(sub)

一行:

1
println('http://localhost:8081/artifactory/api/storage/myrepo/sub1/file.zip'.split('/')[-2])

不拆分,索引:

1
2
3
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])


尝试将您的代码包含在DSL语言的"脚本"标签中,如以下代码所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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]}"
        }
      }
    }
  }
}

执行上面的代码,我在控制台上得到以下结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[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方法:

1
2
3
4
5
6
7
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
}?