根据最后两次出现的分隔符将字符串拆分为两个

时间:2014-05-28 12:21:38

标签: ruby-on-rails regex string

我需要根据最后两次出现的相同分隔符将字符串拆分为两个。

Example:

"this_is_an_example".split_by_last_two_occurance("_") => #[this_is, an_example]

"this_is_an_example_string".split_by_last_two_occurance("_")  => #["this_is_an", "example_string"]

据我所知,

splitted_string = "this_is_an_example_string".split("_")

string_array = [splitted_string[0..-3].join("_"), splitted_string[-3,-1].join("_")]
=> #["this_is_an", "example_string"]

这看起来不是一种有效的方法。 还有其他办法吗?

1 个答案:

答案 0 :(得分:2)

使用正则表达式:

"this_is_an_example_string".split(/_(?=[^_]*_[^_]*$)/)
# => ["this_is_an", "example_string"]
相关问题