Reputation: 1948
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.
Upvotes: 23
Views: 60874
Reputation: 205
Here is an example using regular expressions
String regex = /(v\d)(\d|\.)*/
def clean = { text ->
text?.replaceAll(regex,'')?.trim()
}
assert 'v1.11' ==~ regex
assert clean(null) == null
assert clean('asdf v1.0') == 'asdf'
assert clean('jkl v3.04') == 'jkl'
assert clean('John Kramer v1.1') == 'John Kramer'
assert clean('Kramer v Kramer v9.51') == 'Kramer v Kramer'
assert clean('A very hungry caterpillar v2.6') == 'A very hungry caterpillar'
Upvotes: 2
Reputation: 93173
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
Upvotes: 2
Reputation: 72844
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)
Upvotes: 49
Reputation: 3256
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'
Upvotes: 5