首页 > 解决方案 > 无法在 groovy DSL 中拆分字符串并且没有多行

问题描述

我正在尝试在 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”。

标签: jenkinsgroovyjenkins-pipeline

解决方案


您确定您正确地执行 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])

推荐阅读