【问题标题】:Not able to split string in groovy DSL and there is no multi-line无法在 groovy DSL 中拆分字符串并且没有多行
【发布时间】:2018-08-17 16:05:29
【问题描述】:

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

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

它不会拆分它并在 arr[0] 中返回自身。 我不确定这是否是一个错误。请让我知道 groovy 中是否有其他方法可以从 URL 字符串中获取“sub1”。

【问题讨论】:

标签: jenkins groovy jenkins-pipeline


【解决方案1】:

你确定你做的 DSL 脚本正确吗?由于 groovy 代码看起来没问题。 尝试跳过声明类型

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])

【讨论】:

  • 那个 split() 本身不起作用。我不确定为什么会这样。
  • 你使用什么版本的 groovy?您有任何异常、错误吗?
  • 尝试不拆分,我添加了变体。
【解决方案2】:

尝试将您的代码包含在 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
}​

【讨论】:

  • 在第一个解决方案中,由于无法找到方法而出现错误,而第二个解决方案将无法工作,因为我需要找到值“sub1”。所以匹配是行不通的。
  • 我已经更新了第一种方法,并提供了它有帮助的完整示例。这在我当地的 Jenkins 上对我有用(每次运行时都会显示绿色)。也许您的完整脚本缺少某些内容,请注意您使用的管道部分。
  • 我有一个使用 Jenkins 插件获取 Artifactory 的类,并且在我尝试拆分字符串的方法中。
猜你喜欢
  • 1970-01-01
  • 2018-11-17
  • 2020-06-03
  • 2020-12-19
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 2017-08-29
  • 2017-06-08
相关资源
最近更新 更多