1) sub Try sub
with the specified regular expression, which takes the shortest string to a digit, a digit, and then the next and replaces it with a digit:
sub(".*?(\\d).*", "\\1", string)
giving:
[1] "3"
This also works if string
is a vector of strings.
2) strapplyc You can also use strapplyc
from gsubfn , in which case you could use an even simpler regular expression:
strapplyc(string, "\\d", simplify = TRUE)[1]
gives the same or uses this, which gives the same answer again, but also works if string
is a string
vector:
sapply(strapplyc(string, "\\d"), "[[", 1)
source share