简体   繁体   English

如何从右侧分割字符串

[英]How to split a string from the right side

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 : 使用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. 如果str_a不包含,则上面的代码将返回空字符串。 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. 如果您知道输入字符串的格式,@ falsetru建议是最好的,但是如果输入中根本没有逗号,它将返回空字符串。 Simple regexp 简单的正则表达式

str_a.gsub /,[^,]*$/, ''

will return the input string intouch in such a case. 在这种情况下将返回输入字符串intouch。 Plus you have an ability to modify your input inplace with gsub! 另外,你必须与就地修改输入的能力gsub! .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM