Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy extract substring before character

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.

like image 878
Anonymous Human Avatar asked Nov 14 '14 20:11

Anonymous Human


People also ask

How do I get part of a String in Groovy?

Groovy - subString() Return Value − The specified substring. String substring(int beginIndex, int endIndex) − Pad the String with the padding characters appended to the right.

How do I cut a String in Groovy?

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".

How is Groovy String expressed?

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.


3 Answers

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)
like image 138
M A Avatar answered Oct 19 '22 20:10

M A


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'
like image 45
BalRog Avatar answered Oct 19 '22 18:10

BalRog


input[0..(input.lastIndexOf('v') - 1)].trim()

details

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

like image 2
Abdennour TOUMI Avatar answered Oct 19 '22 20:10

Abdennour TOUMI