How to split the string from the second occurrence of the character
str = "20050451100_9253629709-2-2"
I need the output
["20110504151100_9253629709-2", "2"]
To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.
Python split() method is used to split the string into chunks, and it accepts one argument called separator. A separator can be any character or a symbol. If no separators are defined, then it will split the given string and whitespace will be used by default.
There's nothing like a one-liner :)
str.reverse.split('-', 2).collect(&:reverse).reverse
It will reverse the string, split by '-' once, thus returning 2 elements (the stuff in front of the first '-' and everything following it), before reversing both elements and then the array itself.
Edit
*before, after = str.split('-')
puts [before.join('-'), after]
You could use regular expression matching:
str = "20050451100_9253629709-2-2"
m = str.match /(.+)-(\d+)/
[m[1], m[2]] # => ["20050451100_9253629709-2", "2"]
The regular expression matches "anything" followed by a dash followed by number digits.
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