This approach makes the decimal point and decimal fraction optional and allows multiple numbers to be extracted:
str <- " test 3.1 test 5"
as.numeric(unlist(regmatches(str,
gregexpr("[[:digit:]]+\.*[[:digit:]]*",str))
) )
#[1] 3.1 5.0
The concern about negative numbers can be address with optional perl style look-ahead:
str <- " test -4.5 3.1 test 5"
as.numeric(unlist(regmatches(str,gregexpr("(?>-)*[[:digit:]]+\.*[[:digit:]]*",str, perl=TRUE))))
#[1] -4.5 3.1 5.0
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…