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"]
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.
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 .
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 .
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"]
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With