0

Say I have a string like this :

years<-c("IMG_Sr 179 P.jpg", "IMG_Sr 18 L (2).jpg", "IMG_Sr 182 P.jpg")

The output I expect from this is : c(179, 18,182)

What can I do for this?

  • Try regular expression – מתניה אופן May 18 '21 at 18:23
  • Specifically, remove the "IMG_Sr " part at the beginning of the string and then remove everything that comes after the following number, i.e. the " P.jpg" and so on things. – deschen May 18 '21 at 18:27
  • Does this answer your question? [R extract first number from string](https://stackoverflow.com/questions/23323321/r-extract-first-number-from-string) – slamballais May 18 '21 at 18:32
  • Does this answer your question? [How to extract numbers from a mixed string in R](https://stackoverflow.com/questions/67521189/how-to-extract-numbers-from-a-mixed-string-in-r) – bird May 18 '21 at 18:36

2 Answers2

0

You could use this

    readr::parse_number(years)
0

If your desired output is the only part of the string that is a number surrounded by spaces then you can use:

gsub(".* (\\d*) .*", "\\1", years)

fisher-j
  • 68
  • 7
  • This worked. what if I need an output like this : ` c(179 P, 18 L,182 P)` – Ashish Nambiar May 19 '21 at 07:00
  • `gsub(".* ([[:digit:]]* [[:alpha:]]).*", "\\1", years)` gets you numbers after a space followed by space followed by a single letter. ([[:digit:]] is pretty much the same as \\d) – fisher-j May 19 '21 at 16:44
  • thank you! Can you tell me where I can learn the basics of how you specify these patterns using Regex? – Ashish Nambiar May 20 '21 at 05:09
  • I'd reccommend [regexone.com](https://regexone.com/) followed by issuing the command: `?regex` in an R session for a quick introduction to regular expressions. – fisher-j May 20 '21 at 15:26