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"]
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 n
th 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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With