Divida la cadena en dos en función de las dos últimas ocurrencias de un delimitador
Frecuentes
Visto 110 equipos
0
I need to split a string into two based on last two occurrence of a same delimiter.
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"]
As far as I tried,
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"]
This doesn't looks like an efficient way to do it. Is there any other way to it?
1 Respuestas
2
Usando la expresión regular:
"this_is_an_example_string".split(/_(?=[^_]*_[^_]*$)/)
# => ["this_is_an", "example_string"]
contestado el 28 de mayo de 14 a las 13:05
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas ruby-on-rails regex string or haz tu propia pregunta.