I've browsed half stackoverflow in search of this but nothing seems to perfectly match, sorry if wrong.
I've got a string with the format:
fname <-'FS1_SCN0.83_axg3.csv'
I'd like to extract the second number, which happens to be a decimal, but could also be an integer, and get as a result 0.83 (or 3 if integer). Closest I've got is this:
gsub("[^0-9.]","\\2",fname)
that produces all the numbers and decimal markers in fname (10.833.), but as a whole string.
Thanks in advance, p.
To get the second number,
regmatches(x, regexpr("^\\D*\\d+\\D*\\K\\d+(?:\\.\\d+)?", x, perl=TRUE))
Demo
or
sub("^\\D*\\d+\\D*(\\d+(?:\\.\\d+)?).*", "\\1", x, perl=TRUE)
Example:
> x <-'FS1_SCN0.83_axg3.csv'
> regmatches(x, regexpr("^\\D*\\d+\\D*\\K\\d+(?:\\.\\d+)?", x, perl=TRUE))
[1] "0.83"
> sub("^\\D*\\d+\\D*(\\d+(?:\\.\\d+)?).*", "\\1", x, perl=TRUE)
[1] "0.83"
For more general case,
regmatches(x, regexpr("^\\D*\\d+(?:\\.\\d+)?\\D*\\K\\d+(?:\\.\\d+)?", x, perl=TRUE))
sub("^\\D*\\d+(?:\\.\\d+)?\\D*(\\d+(?:\\.\\d+)?).*", "\\1", x, perl=TRUE)
OR
Just specify the index number to get the number you want.
> regmatches(fname, gregexpr("\\d+(?:\\.\\d+)?", fname))[[1]][2]
[1] "0.83"
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