Reputation: 4035
I am trying to split a URL http://localhost:8081/artifactory/api/storage/myrepo/sub1/file.zip in groovy DSL of Jenkins. It is a single line string. But following code does not work
String[] arr= string_var.split('/');
String[] arr=string_var.split('\\/');
It does not split it and returns itself in arr[0]. I am not sure if it is a bug. Please let me know if any other way is there in groovy to get "sub1" from URL string.
Upvotes: 0
Views: 2075
Reputation: 180
Are you sure that you doing DSL script correctly? As the groovy code looks to be OK. Try to skip declaring types
def url_str = 'http://localhost:8081/artifactory/api/storage/myrepo/sub1/file.zip'
def sub = url_str.split('/')[-2]
println(sub)
in one line:
println('http://localhost:8081/artifactory/api/storage/myrepo/sub1/file.zip'.split('/')[-2])
no split, indexes:
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])
Upvotes: 2
Reputation: 91
Try enclosing your code inside a 'script' tag of DSL language like the following piece of code:
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]}"
}
}
}
}
}
Executing code above I get this result on the console:
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
http:
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Thus, giving the expected 'http:' String
Another Groovy way to get the string 'sub1' (regex):
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
}
Upvotes: 0