Reputation: 12082
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"]
Upvotes: 11
Views: 16523
Reputation: 136
string.gsub(/^[^-]+-[^-]+-/,'')
^
is start[^-]
is a single character except dash[^-]+
makes item 2 one or more single characters except dashes-
is a dash[^-]+-
is a repeat of abovegsub
removes the characters that match the patternUpvotes: 0
Reputation: 26488
"20050451100_9253629709-2-2"[/^([^-]*\-[^-]*)\-(.*)$/]
[$1, $2] # => ["20050451100_9253629709-2", "2"]
That will match any string, splitting it by the second occurrence of -
.
Upvotes: 3
Reputation: 9561
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]
Upvotes: 11
Reputation: 6076
You could split it apart and join it back together again:
str = "20050451100_9253629709-2-2"
a = str.split('-')
[a[0..1].join('-'), a[2..-1].join('-')]
Upvotes: 2
Reputation: 10329
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.
Upvotes: 4
Reputation: 20645
If you always have two hyphens you can get the last index of the -
:
str = "20050451100_9253629709-2-2"
last_index = str.rindex('-')
# initialize the array to hold the two strings
arr = []
# get the string characters from the beginning up to the hyphen
arr[0] = str[0..last_index]
# get the string characters after the hyphen to the end of the string
arr[1] = str[last_index+1..str.length]
Upvotes: 4