Groovy提取字符前的子字符串 [英] Groovy extract substring before character

查看:400
本文介绍了Groovy提取字符前的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆像这样的字符串

I have a bunch of strings like

asdf v1.0
jkl v3.04

我所有的字符串都是一组字符,后跟一个空格,然后是"v",然后是一个数字.我想从每个字符串中提取"v"之前的部分以及在"v"之前的空格字符,以便:

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'

在这方面需要一些帮助.我尝试了takeWhile { it != 'v' },但最终在结果字符串中包含了我不想要的'v'之前的空格.

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.

推荐答案

您可以简单地提取子字符串:

You can simply extract the substring:

input.substring(0, input.lastIndexOf(" v"))

要获得v之后的零件:

input.substring(input.lastIndexOf(" v") + 2)

这篇关于Groovy提取字符前的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆