在最后一个字符的出现位置拆分字符串

5

我有以下字符串:

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

我想把上面的字符串按最后一个冒号(:)分割,以便得到这两个元素:

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

问题不清楚。您是想按冒号分割(保留冒号),还是按冒号后面的空格分割(去掉空格)? - sawa
你读了这个问题吗?? - tokhi
2个回答

4

尝试简单的代码:

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

2

试一试

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接