0

I'm using Groovy split() method and I have the following code

def value = '-t "not @healthcheck"'

println(value.split(/[^\s"']+|"([^"]*)"|'([^']*)'/))

I grabbed the regular expression from Regex for splitting a string using space when not surrounded by single or double quotes

Basically I want to split my string by whitespace but not if it's surrounded by single/double quotes.

My end result I want is [-t, not @healthcheck] but I'm getting [, , ]. I don't understand why all the values are empty. Maybe my regular expression isn't correct or I don't understand groovy syntax messing up something.

cfrick
  • 32,094
  • 5
  • 49
  • 62
Alex Len
  • 43
  • 3

1 Answers1

0

I think you should not use split() here. I'd rather use pattern matching like so:

def value = '-t "not @healthcheck"    -t "111" -v "222" -c ahska@jhd'

def list = ( value =~ /(-[a-z]+)\s+"?([^"-]+)"?/ ).collect{ _, key, val -> [ key, val ] }

println list.join( '\n' )

prints:

[-t, not @healthcheck]
[-t, 111]
[-v, 222]
[-c, ahska@jhd]
injecteer
  • 17,769
  • 3
  • 41
  • 79