I have a bunch of strings like
asdf v1.0
jkl v3.04
all my strings are a group of characters followed by a space then 'v' then a number. I want to extract from each string, the part that comes before the 'v' and the space character preceeding the 'v' so that:
asdf v1.0 becomes 'asdf'
jkl v3.04 becomes 'jkl'
just need some help with this. I tried takeWhile { it != 'v' }
but that ends up including the space before the 'v' in the result string which I don't want.
Groovy - subString() Return Value − The specified substring. String substring(int beginIndex, int endIndex) − Pad the String with the padding characters appended to the right.
The Groovy community has added a take() method which can be used for easy and safe string truncation. Both take() and drop() are relative to the start of the string, as in "take from the front" and "drop from the front".
Groovy offers a variety of ways to denote a String literal. Strings in Groovy can be enclosed in single quotes ('), double quotes (“), or triple quotes (“””). Further, a Groovy String enclosed by triple quotes may span multiple lines.
You can simply extract the substring:
input.substring(0, input.lastIndexOf(" v"))
To get the part after the v
:
input.substring(input.lastIndexOf(" v") + 2)
I think, given the criteria as stated, that the following would give correct results in places where the chosen solution would not:
String stringParser(String inputString) {
inputString ? inputString.split(/ v\d/)[0] : ''
}
Some sample tests:
assert stringParser('John Kramer v1.1') == 'John Kramer'
assert stringParser('Kramer v Kramer v9.51') == 'Kramer v Kramer'
assert stringParser('A very hungry caterpillar v2.6') == 'A very hungry caterpillar'
input[0..(input.lastIndexOf('v') - 1)].trim()
String str = 'jkl v3.04'
// index of last "v" char is 4
assert str[4..-1] == 'v3.04'
assert str[0..(4 - 1 )].trim() == 'jkl'
You do not have to be surprised: i am a very former groovy programmer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With