Extract decimal numbers from a string

I have a line such as "3.1 ml" or "abc 3.1 xywazw"

I want to extract "3.1" from this line. I found a lot of stackoverflow questions about extracting numbers from a character string, but no solution works for decimal numbers.

+6
source share
4 answers

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)))) #[1] -4.5 3.1 5.0 
+11
source

Use the stringr library:

 x<-"abc 3.1 xywazw" str_extract(x, "\\d+\\.*\\d*") [1] "3.1" 
+9
source

The regular expression for the floating point number from http://www.regular-expressions.info/floatingpoint.html with a minor adjustment for working in R.

 s <- "1e-6 dkel" regmatches(s,gregexpr("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?",s)) > [[1]] > [1] "1e-6" 
+2
source

You can use regular expressions:

 > str <- " test 3.1 test" > as.numeric(regmatches(str,regexpr("[[:digit:]]+\\.[[:digit:]]+",str))) [1] 3.1 

regexpr returns the starting position and length of the matched string. regmatches returns matches. Then you can convert it to a number.

+1
source

Source: https://habr.com/ru/post/955509/


All Articles