如何从第二次出现的字符开始拆分字符串
str = "20050451100_9253629709-2-2"
I need the output
["20110504151100_9253629709-2", "2"]
没有什么比一行代码更好了 :)
str.reverse.split('-', 2).collect(&:reverse).reverse
这将会反转字符串并且只按照'-'分割一次,因此返回2个元素(第一个'-'前面的内容和其后面所有的内容)。然后再反转这两个元素以及整个数组。
编辑
*before, after = str.split('-')
puts [before.join('-'), after]
-
的最后一个索引: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]
str = "20050451100_9253629709-2-2"
m = str.match /(.+)-(\d+)/
[m[1], m[2]] # => ["20050451100_9253629709-2", "2"]
"20050451100_9253629709-2-2"[/^([^-]*\-[^-]*)\-(.*)$/]
[$1, $2] # => ["20050451100_9253629709-2", "2"]
这将匹配任何字符串,并通过第二个-
字符进行分割。
str.match(/^([^-]*\-[^-]*)\-(.*)$/).to_a[1..-1]
- Kelvinstr = "20050451100_9253629709-2-2"
a = str.split('-')
[a[0..1].join('-'), a[2..-1].join('-')]
string.gsub(/^[^-]+-[^-]+-/,'')
^
表示开头[^-]
表示除了破折号以外的单个字符[^-]+
表示一个或多个除了破折号以外的单个字符-
表示破折号[^-]+-
表示上述内容的重复gsub
函数删除与该模式匹配的字符