最后一次出现字符后分割字符串

时间:2023-01-01 19:43:36

I have below string:

我有以下字符串:

this sentence: should be: splited after last colon: sentence

so I want to split the sentence above after the last colon : occurrence as below:

所以我想在最后一个冒号之后拆分上面的句子:出现如下:

["this sentence: should be: splited after last colon:", "sentence"]

any help?

2 个解决方案

#1


4  

Try simple code:

尝试简单的代码:

s = 'this sentence: should be: splited after last colon: sentence'
s =~ /(.*):(.*)?/
[ $1 << ':', $2 ]
# => ["this sentence: should be: splited after last colon:", " sentence"]

#2


1  

Have a try with

尝试一下

str = "this sentence: should be: splited after last colon: sentence"
last_pos = str.rindex(/\:/)
arr = [str[0..last_pos].strip, str[last_pos + 1 .. str.length].strip]

=>["this sentence: should be: splited after last colon:", "sentence"] 

#1


4  

Try simple code:

尝试简单的代码:

s = 'this sentence: should be: splited after last colon: sentence'
s =~ /(.*):(.*)?/
[ $1 << ':', $2 ]
# => ["this sentence: should be: splited after last colon:", " sentence"]

#2


1  

Have a try with

尝试一下

str = "this sentence: should be: splited after last colon: sentence"
last_pos = str.rindex(/\:/)
arr = [str[0..last_pos].strip, str[last_pos + 1 .. str.length].strip]

=>["this sentence: should be: splited after last colon:", "sentence"]