Mr. Black
Mr. Black

Reputation: 12082

Split string from the second occurrence of the character

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

Answers (6)

Node Noodler
Node Noodler

Reputation: 136

string.gsub(/^[^-]+-[^-]+-/,'')
  1. ^is start
  2. [^-]is a single character except dash
  3. [^-]+makes item 2 one or more single characters except dashes
  4. -is a dash
  5. [^-]+-is a repeat of above
  6. Using gsub removes the characters that match the pattern

Upvotes: 0

Douglas F Shearer
Douglas F Shearer

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

gnab
gnab

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

seph
seph

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

hallidave
hallidave

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

McStretch
McStretch

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

Related Questions