Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract n-decimal from string

Tags:

regex

r

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.

like image 894
user3310782 Avatar asked Dec 04 '25 16:12

user3310782


1 Answers

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"
like image 161
Avinash Raj Avatar answered Dec 06 '25 05:12

Avinash Raj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!