簡體   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