Reputation: 348
> str=" 9.48 12.89 13.9 6.79 "
> strsplit(str,split="\\s+")
[[1]]
[1] "" "9.48" "12.89" "13.9" "6.79"
> unlist(strsplit(str,split="\\s+"))->y
> y[y!=""]
[1] "9.48" "12.89" "13.9" "6.79"
How can i get it by a single regular expression with strsplit , not to oparate it with
y[y!=""]
?
Upvotes: 1
Views: 76
Reputation: 17189
If you want to extract just the numbers perhaps following regex would do.
regmatches(str, gregexpr("[0-9.]+", text = str))[[1]]
## [1] "9.48" "12.89" "13.9" "6.79"
To capture -ve numbers you can use following
str = " 9.48 12.89 13.9 --6.79 "
regmatches(str, gregexpr("\\-{0,1}[0-9.]+", text = str))[[1]]
## [1] "9.48" "12.89" "13.9" "-6.79"
Upvotes: 1
Reputation: 193517
I would just trim the string before splitting it:
strsplit(gsub("^\\s+|\\s+$", "", str), "\\s+")[[1]]
# [1] "9.48" "12.89" "13.9" "6.79"
Alternatively, it is pretty direct to use scan
in this case:
scan(text=str)
# Read 4 items
# [1] 9.48 12.89 13.90 6.79
Upvotes: 2