I have a string such as "3.1 ml"
or "abc 3.1 xywazw"
I'd like to extract "3.1"
from this string. I have found many questions on stackoverflow about the extraction of numbers from a character string, but no solution works for the case of decimal numbers.
Select a cell and type this formula =A1-TRUNC(A1) (A1 is the cell you want to extract decimal value from) into the Formula Bar, and then press Enter key. Keep selecting the first result cell, and drag fill handle down to get all results. You can see the decimal values are extracted with sign as below screenshot shown.
We use \d+\. \d+ regular expression in python to get non digit characters from a string. Where, \d returns a match where the string contains digits (numbers from 0 9)
The TRUNC function simply truncates (i.e. removes) decimal values if they exist – it doesn't do any rounding. The TRUNC function returns the integer portion of the number which is then subtracted from the original value. The result is the decimal portion of the number.
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
Use the stringr
library:
x<-"abc 3.1 xywazw"
str_extract(x, "\\d+\\.*\\d*")
[1] "3.1"
Regular expression for floating point number from http://www.regular-expressions.info/floatingpoint.html with minor adjustment to work in R.
s <- "1e-6 dkel"
regmatches(s,gregexpr("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?",s))
> [[1]]
> [1] "1e-6"
You can use regular expressions :
> str <- " test 3.1 test"
> as.numeric(regmatches(str,regexpr("[[:digit:]]+\\.[[:digit:]]+",str)))
[1] 3.1
regexpr
returns the start position and length of the matched string. regmatches
returns the matches. You can then convert it to a number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With