问题
I would like to extract the first string from a vector. For example,
y<- c('london/hilss', 'newyork/hills', 'paris/jjk')
I want to get the string before the symbol"/" i.e.,
location
london
newyork
paris
回答1:
A very simple approach with gsub
gsub("/.*", '', y)
[1] "london" "newyork" "paris"
回答2:
Your example is simple, for a more general case like
y<- c('london/hilss', 'newyork.hills', 'paris-jjk')
maybe following will do better?
stringr::str_extract(y, '\\w*')
回答3:
stringr::str_extract(a, '\\b*')
回答4:
This regex will also work fine.
Regex: ^[^\/]+
It will start matching from beginning of string until a /
is found.
^
outside character class []
is anchor for beginning of string.
While ^
inside character class means negated character class.
Regex101 Demo
来源:https://stackoverflow.com/questions/43900073/obtaining-first-word-in-the-string