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)?
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.
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.
split("\n");
groovy:000> sliceMe = "nnYYYYYYnnnnnnnnnn" ===> nnYYYYYYnnnnnnnnnn groovy:000> sliceMe[2..7] ===> YYYYYY
Note the difference in the length being 1 less.
You inherit all the Java methods off String
so sliceMe.substring(2,7)
should do the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With