To get a SubString in Groovy, separated by a character

Consider the line below

String names = "Bharath-Vinayak-Harish-Punith" 

I want to get the output as a string containing only Bharath . (String until the first occurrence of the "-" operator). Can anyone tell me how we can do this?

+6
source share
5 answers

In general, I agree with the split method in the previous answer, but when returning the first line, the substring method is the same amount of work for the programmer (and, for insanely large lines, less computational work):

 String result = names.substring(0, names.indexOf('-')) 
+13
source

If you are using Groovy 2.0 (released yesterday), you can do:

 String names = 'Bharath-Vinayak-Harish-Punith' String result = names.takeWhile { it != '-' } assert result == 'Bharath' 
+5
source

You can use split:

 def theName = names.split(/-/)[0] 

split returns an array of String, then gets the first element of the array.

+4
source
 def names= 'Bharath-Vinayak-Harish-Punith' assert "Bharath" == (names =~ /^(.*?)\-/)[0][1] 
+1
source

if you have the Apache Commons Lang library (which is part of various other frameworks like Grails):

  def result = StringUtils.substringBefore(names, '-') 

Regards, Bjorn

+1
source

Source: https://habr.com/ru/post/919301/


All Articles