开发者

Split string from the second occurrence of the character

How to split the string from the second occurrence of the charac开发者_如何学运维ter

str = "20050451100_9253629709-2-2"

I need the output 
["20110504151100_9253629709-2", "2"]


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 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]


"20050451100_9253629709-2-2"[/^([^-]*\-[^-]*)\-(.*)$/]
[$1, $2] # => ["20050451100_9253629709-2", "2"]

That will match any string, splitting it by the second occurrence of -.


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('-')]


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜