Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract only number between commas

Tags:

regex

r

gsub

I have a returned string like this from my code: (<C1>, 4.297, %) And I am trying to extract only the value 4.297 from this string using gsub command:

Fat<-gsub("\\D", "", stringV)

However, this extracts not only 4.297 but also the number '1' in C1. Is there a way to extract only 4.297 from this string, please can you help.

Thanks

like image 259
Phuong Ho Avatar asked May 03 '26 23:05

Phuong Ho


1 Answers

How about this?

# Your sample character string
ss <- "(<C1>, 4.297, %)";

gsub(".+,\\s*(\\d+\\.\\d+),.+", "\\1", ss)
#[1] "4.297"

or

gsub(".+,\\s*([0-9\\.]+),.+", "\\1", ss)

Convert to numeric with as.numeric if necessary.

like image 61
Maurits Evers Avatar answered May 05 '26 13:05

Maurits Evers



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!