How to extract version number from String in R

Viewed 84

Using R, stringr or any other package how do I get a version number with this rule:

start when you see " v" and end when you see "_" or " "

Here is an example

example <- c("daata v2.0 jkdfajfkdal fdadjfk 398432", "data 432 dfafd v4.0_ dfakfld")

I want:

ex2 <- c("v2.0", "v4.0")

Many thanks!

1 Answers

We can use regexpr/regmatches in base R to match the v followed by one or more digits (\\d+) followed by a dot (.) and one or more digits

regmatches(example, regexpr("v[0-9]+(\\.[0-9]+)?", example))
#[1] "v2.0" "v4.0"

Here we assume that all the elements have the pattern. If they don't have a pattern, then regexpr returns an index of -1 and thus we don't get the value corresponding to it. So, before we do the regmatches, should change those -1 or use an index to return wherever it is -1 as NA. But an easier option is str_extract which returns NA where there are no match

library(stringr)
str_extract(example, "v[0-9]+(\\.[0-9]+)?")
Related