Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string on the last occurrence of a character [closed]

I have the string below:

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

I want to split the above string on the last colon (:) such that the resulting array will contain these two elements:

["this sentence: should be: splited after last colon:", "sentence"]
like image 891
tokhi Avatar asked Dec 24 '13 09:12

tokhi


People also ask

How do you split the last character of a string?

To split a string on the last occurrence of a substring:, use the lastIndexOf() method to get the last index of the substring and call the slice() method on the string to get the portions before and after the substring you want to split on.

How do you split at last delimiter?

Use the str. rsplit() method with maxsplit set to 1 to split a string on the last occurrence of a delimiter, e.g. my_str. rsplit(',', 1) . The rsplit() method splits from the right, and only performs a single split when maxsplit is set to 1 .

How do you find the last occurrence of a character in a string is?

strrchr() — Locate Last Occurrence of Character in String The strrchr() function finds the last occurrence of c (converted to a character) in string . The ending null character is considered part of the string . The strrchr() function returns a pointer to the last occurrence of c in string .


2 Answers

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"]
like image 197
Малъ Скрылевъ Avatar answered Sep 27 '22 23:09

Малъ Скрылевъ


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"] 
like image 31
Bachan Smruty Avatar answered Sep 27 '22 23:09

Bachan Smruty