obtaining first word in the string [duplicate]

丶灬走出姿态 提交于 2019-12-04 06:56:19

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!