Split String and Take Last Element

Java: Get last element after split

Save the array in a local variable and use the array's length field to find its length. Subtract one to account for it being 0-based:

String[] bits = one.split("-");
String lastOne = bits[bits.length-1];

Caveat emptor: if the original string is composed of only the separator, for example "-" or "---", bits.length will be 0 and this will throw an ArrayIndexOutOfBoundsException. Example: https://onlinegdb.com/r1M-TJkZ8

Getting the last element of a split string array





const str = "hello,how,are,you,today?"
const pieces = str.split(/[\s,]+/)
const last = pieces[pieces.length - 1]

console.log({last})

Split string and take last element

The way to do it in SQL :

SELECT SUBSTRING( string , LEN(string) -  CHARINDEX('/',REVERSE(string)) + 2  , LEN(string)  ) FROM SAMPLE;

JSFiddle here http://sqlfiddle.com/#!3/41ead/11

Python - Get Last Element after str.split()

Use a list comprehension to take the last element of each of the split strings:

ids = [val[-1] for val in your_string.split()]

R get last element from str_split

As the comment on your question suggests, this is suitable for gsub:

gsub("^.*_", "", string_thing)

I'd recommend you take note of the following cases as well.

string_thing <- c("I_AM_STRING", "I_AM_ALSO_STRING_THING", "AM I ONE", "STRING_")
gsub("^.*_", "", string_thing)
[1] "STRING" "THING" "AM I ONE" ""

Split string and get last element

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.

Select last element quickly after a .Split()

If you're using .NET 3.5 or higher, it's easy using LINQ to Objects:

stringCutted = myString.Split('/').Last();

Note that Last() (without a predicate) is optimized for the case where the source implements IList<T> (as a single-dimensional array does) so this won't iterate over the whole array to find the last element. On the other hand, that optimization is undocumented...

Split string and not take right of last element Presto

If the goal is to remove the last / and everything after that - you can try using regexp_replace:

 select regexp_replace('Hello/Hi/Howdy/Bye', '(\/[^\/]*$)', '')

Output:



Leave a reply



Submit