Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string and get last element

Let's say I have a column which has values like:

foo/bar chunky/bacon/flavor /baz/quz/qux/bax 

I.e. a variable number of strings separated by /.

In another column I want to get the last element from each of these strings, after they have been split on /. So, that column would have:

bar flavor bax 

I can't figure this out. I can split on / and get an array, and I can see the function INDEX to get a specific numbered indexed element from the array, but can't find a way to say "the last element" in this function.

like image 375
Max Williams Avatar asked May 23 '16 11:05

Max Williams


People also ask

How do you split a string and get the last element?

To split a string and get the last element of the array, call the split() method on the string, passing it the separator as a parameter, and then call the pop() method on the array, e.g. str. split(','). pop() . The pop() method will return the last element from the split string array.

How do you find the last element in a string array?

To get the last element of the array, we can pass in index -1 as the start index to return an array that has the last element of the array. We don't need the end index since the default value for the end index is the last index of the array. We use [0] to get the first element of the array returned by slice .

How do you get the last string split in Python?

Use the str. rsplit() method with maxsplit set to 1 to split a string and get the last element. The rsplit() method splits from the right and will only perform a single split when maxsplit is set to 1 .


2 Answers

Edit: this one is simplier:

=REGEXEXTRACT(A1,"[^/]+$") 

You could use this formula:

=REGEXEXTRACT(A1,"(?:.*/)(.*)$") 

And also possible to use it as ArrayFormula:

=ARRAYFORMULA(REGEXEXTRACT(A1:A3,"(?:.*/)(.*)$")) 

Here's some more info:

  • the RegExExtract function
  • Some good examples of syntax
  • my personal list of Regex Tricks

This formula will do the same:

=INDEX(SPLIT(A1,"/"),LEN(A1)-len(SUBSTITUTE(A1,"/",""))) 

But it takes A1 three times, which is not prefferable.

like image 59
Max Makhrov Avatar answered Sep 21 '22 18:09

Max Makhrov


Also possible, perhaps best on a copy, with Find:

.+/  

(Replace with blank) and Search using regular expressions ticked.

like image 36
pnuts Avatar answered Sep 21 '22 18:09

pnuts