繁体   English   中英

如何从右侧分割字符串

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

我如何用','从右边分割字符串? 从此字符串:

str_a = "#37/1, New Ray Street, 24th mains,2nd cross, Bangalore Karnataka India"

我想要一个输出:

"#37/1, New Ray Street, 24th mains,2nd cross"

使用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"

更新

如果str_a不包含,则上面的代码将返回空字符串。 如果可能会使用以下代码。

str_a = "#37/1"
head, sep, tail = str_a.rpartition(',') # => ["", "", "#37/1"]
sep == '' ? tail : head # OR   sep[0] ? head : tail
# => "#37/1"

如果您知道输入字符串的格式,@ falsetru建议是最好的,但是如果输入中根本没有逗号,它将返回空字符串。 简单的正则表达式

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

在这种情况下将返回输入字符串intouch。 另外,你必须与就地修改输入的能力gsub!

暂无
暂无

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

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