Get characters before first space

2019-02-12 20:01发布

I am looking for a grep way to obtain the characters in a string prior to the first space.

I have hacked the following function, as i could not figure out how to do it using the grep type commands in R.

Could someone help with the grep solution - if there is one ...

beforeSpace <- function(inWords) {
    vapply(inWords, function(L) strsplit(L, "[[:space:]]")[[1]][1], FUN.VALUE = 'character')
}
words <- c("the quick", "brown dogs were", "lazier than quick foxes")
beforeSpace(words)

R>          the quick         brown dogs were lazier than quick foxes 
              "the"                 "brown"                "lazier" 

And do let me know if there's a better way than grep (or my function, beforeSpace) to do this.

标签: r grep substring
3条回答
戒情不戒烟
2楼-- · 2019-02-12 20:24

Or just sub, with credit to @flodel:

sub(" .*", "", words)
# and if the 'space' can also be a tab or other white-space:
sub("\\s.*","",words)
#[1] "the"    "brown"  "lazier"
查看更多
女痞
3楼-- · 2019-02-12 20:44

Using stringi

library(stringi) 
stri_extract_first(words, regex="\\w+")
#[1] "the"    "brown"  "lazier"
查看更多
淡お忘
4楼-- · 2019-02-12 20:45

You can use qdap's beg2char (beginning of the string to a particular character) as follows:

x <- c("the quick", "brown dogs were", "lazier than quick foxes")
library(qdap)
beg2char(x)
## [1] "the"    "brown"  "lazier"
查看更多
登录 后发表回答