Split string and get last element

半世苍凉 提交于 2019-11-29 11:17:00

问题


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.


回答1:


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.




回答2:


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

.+/ 

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




回答3:


You can try use this!

You've got the array of String, so you can acess the last element by length

String message =  "chunky/bacon/flavor";
String[] outSplited = message.split("/");

System.out.println(outSplited[outSplited.length -1]);


来源:https://stackoverflow.com/questions/37390009/split-string-and-get-last-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!