Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string from the second occurrence of the character

Tags:

string

ruby

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"]
like image 239
Mr. Black Avatar asked May 11 '11 12:05

Mr. Black


People also ask

How do you split a string at a certain character?

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.

How do you split part of a string in Python?

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.


2 Answers

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]
like image 151
gnab Avatar answered Nov 07 '22 13:11

gnab


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.

like image 36
hallidave Avatar answered Nov 07 '22 14:11

hallidave