Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip everything from an array of strings after certain character

Tags:

string

julia

This rather simple julia issue has got me a little perplexed.

Let's say I have an array of strings of the form "xxx_xxx". Is there a function that will remove everything from "_" onward?

Example

names = ["last1_first1","last2_first2"]

Is there a simple function that will return

["last1","last2"]
like image 311
Tim Avatar asked Dec 22 '22 18:12

Tim


1 Answers

You are looking for split:

julia> names  = ["last1_first1", "last2_first2"]
2-element Array{String,1}:
 "last1_first1"
 "last2_first2"

julia> split.(names, "_")
2-element Array{Array{SubString{String},1},1}:
 ["last1", "first1"]
 ["last2", "first2"]

Note that I am using the dot broadcasting syntax split.() here to apply the split function elementwise to the array of names.

For completeness one way of pulling out the last elements is:

julia> hcat(split.(names, "_")...)[1, :]
2-element Array{SubString{String},1}:
 "last1"
 "last2"

As Cameron points out in the comments, if it is (as in this example) the first element you're after, you can replace the hcat and splatting with:

julia> first.(split.(names, "_"))
2-element Array{SubString{String},1}:
 "last1"
 "last2"

This is slightly less flexible for those cases where you want the nth index. For those cases you can broadcast getindex and pass it the index of the element you're after:

julia> julia> getindex.(split.(names, "_"), 2)
2-element Array{SubString{String},1}:
 "first1"
 "first2"

Alternatively building on the regex idea in your own answer, you can simply do:

julia> replace.(names, r"_.*" => "")
2-element Array{String,1}:
 "last1"
 "last2"
like image 106
Nils Gudat Avatar answered Jun 09 '23 22:06

Nils Gudat