srishti
srishti

Reputation: 31

String extract, to extract number from a text

How can I extract a 3 digit number from text which is not a date?

Example:

"she is born on 02-05-1934 and she is 200 years old." 

So, how do i extract 200 from here

I was using the code:

str_extract(data,"[[:digit:]]{3}")

but it's returning the output of -193.

Upvotes: 3

Views: 88

Answers (1)

akrun
akrun

Reputation: 887901

We can use regexlookarounds to specify the digits are preceded by space and followed by space (based on the pattern showed)

library(stringr)
as.numeric(str_extract(str1, "(?<=\\s)\\d+(?=\\s)"))
#[1] 200

data

str1 <- "she is born on 02-05-1934 and she is 200 years old"

Upvotes: 5

Related Questions