How can I split a string from right side by ','
? From this string:
str_a = "#37/1, New Ray Street, 24th mains,2nd cross, Bangalore Karnataka India"
I want an output:
"#37/1, New Ray Street, 24th mains,2nd cross"
Use String#rpartition
:
str_a = "#37/1, New Ray Street, 24th mains,2nd cross, Bangalore Karnataka India"
str_a.rpartition(',')
# => ["#37/1, New Ray Street, 24th mains,2nd cross", ",", " Bangalore Karnataka India"]
str_a.rpartition(',')[0]
# => "#37/1, New Ray Street, 24th mains,2nd cross"
UPDATE
If str_a
does not contain ,
, the above code will return the empty string. Use following code if that could be an issue.
str_a = "#37/1"
head, sep, tail = str_a.rpartition(',') # => ["", "", "#37/1"]
sep == '' ? tail : head # OR sep[0] ? head : tail
# => "#37/1"
While @falsetru suggestion is fairly the best if you know what the input string format is, it will return empty string if there were no commas in the input at all. Simple regexp
str_a.gsub /,[^,]*$/, ''
will return the input string intouch in such a case. Plus you have an ability to modify your input inplace with gsub!
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.