0

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
user3570187
  • 1,743
  • 3
  • 17
  • 34

4 Answers4

11

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*')
Sean Lin
  • 805
  • 4
  • 12
  • `str_extract` returns a character vector, while `str_match` returns a character matrix. @Sean: do you have a preference? It seems to me they're basically the same, though I get annoyed with matrixes. – Nettle Aug 17 '18 at 03:03
2

stringr::str_extract(a, '\\b*')

1

A very simple approach with gsub

gsub("/.*", '', y)
[1] "london"  "newyork" "paris"
cdeterman
  • 19,630
  • 7
  • 76
  • 100
  • Can you explain why `/.*` does not need to be escaped and, when it is, `\\/.*` produces the same result? In other words, `gsub("/.*", '', y)` is the same as `gsub("\\/.*", '', y)` – Nettle Aug 17 '18 at 02:56
  • @Nettle my understanding is that a forward slash does not need to be escaped. By adding `\\` you are basically escaping something that doesn't need to be escaped so nothing changes. – cdeterman Aug 17 '18 at 14:17
0

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

Rahul
  • 2,658
  • 12
  • 28