0

I have strings like this one x <- "123/456/789". I want to do three different things

  1. Get the first word before /, that is, 123
  2. Get the word between two /: 456
  3. Get the last word, the one afte the last /

I know there are some functions like gsub and packages like stingr but I did not find something useful

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
R18
  • 1,476
  • 1
  • 8
  • 17

2 Answers2

1

If you want to read the digits and parse as numbers, you can try

> scan(text = x, sep = "/", quiet = TRUE)
[1] 123 456 789
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
1

You could get it to work using gsub and str_extract from {stringr}:

# Get 123
gsub("/\\d*", "", x)

# Get 456
gsub("/", "", stringr::str_extract(x, "/\\d*/"))

# Get 789
gsub("\\d*/", "", x)

This results in:

[1] "123"

[1] "456"

[1] "789"

In the RegEx, \\d* indicates one or more digits, but if your word consists of other characters you could also use a different indicator.

rjjanse
  • 311
  • 4