This approach makes optional decimal and decimal fractions and allows you to extract multiple numbers:
str <- " test 3.1 test 5" as.numeric(unlist(regmatches(str, gregexpr("[[:digit:]]+\\.*[[:digit:]]*",str)) ) ) #[1] 3.1 5.0
Negative numbers can be addressed by the optional facsimile perl style:
str <- " test -4.5 3.1 test 5" as.numeric(unlist(regmatches(str,gregexpr("(?>-)*[[:digit:]]+\\.*[[:digit:]]*",str, perl=TRUE))))
source share