R: how to find the first digit in a string

r, regex

Solution

Base R

regmatches(string, regexpr("\\d", string))
## [1] "3"

Or using `stringi`

library(stringi)
stri_extract_first(string, regex = "\\d")
## [1] "3"

Or using `stringr`

library(stringr)
str_extract(string, "\\d")
## [1] "3"

Problem

``` string = "ABC3JFD456" ``` Suppose I have the above string, and I wish to find what the first digit in the string is and store its value. In this case, I would want to store the value 3 (since it's the first-occuring digit in the string). `grepl("\\d", string)` only returns a logical value, but does not tell me anything about where or what the first digit is. Which regular expression should I use to find the value of the first digit?

Original source