Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice a string in groovy

I have a 18 character string I want characters 2-8 from. In python I can do this:

sliceMe = "nnYYYYYYnnnnnnnnnn" print sliceMe[2:8] 

prints

YYYYYY 

I am looking for a way to do this same thing in groovy, and every explanation is REALLY long. Whats the elegant accepted way to do this in groovy (or java for that matter)?

like image 918
Mikey Avatar asked May 13 '11 22:05

Mikey


People also ask

How do you slice a string?

The slice() method extracts a part of a string. The slice() method returns the extracted part in a new string. The slice() method does not change the original string. The start and end parameters specifies the part of the string to extract.

How do I remove a substring from a string in Groovy?

Groovy has added the minus() method to the String class. And because the minus() method is used by the - operator we can remove parts of a String with this operator. The argument can be a String or a regular expression Pattern. The first occurrence of the String or Pattern is then removed from the original String.

How do you split a new line in groovy?

split("\n");


2 Answers

groovy:000> sliceMe = "nnYYYYYYnnnnnnnnnn" ===> nnYYYYYYnnnnnnnnnn groovy:000> sliceMe[2..7] ===> YYYYYY 

Note the difference in the length being 1 less.

like image 141
onteria_ Avatar answered Sep 21 '22 21:09

onteria_


You inherit all the Java methods off String so sliceMe.substring(2,7) should do the trick.

like image 42
BZ. Avatar answered Sep 25 '22 21:09

BZ.