从文本中提取数字的字符串提取

3

如何从非日期文本中提取一个三位数?

示例:

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

那么,我如何从这里提取200?
我正在使用以下代码:
str_extract(data,"[[:digit:]]{3}")

但它返回的输出是-193


1
尝试使用 str_extract(str1, "(?<=\\s)\\d+(?=\\s)") - akrun
1
在你的模式中添加空格也应该可以运行。as.numeric(str_extract(data,"\\s[[:digit:]]{3}\\s")) - Ronak Shah
1个回答

5
我们可以使用正则表达式的lookaround语法来指定数字前面和后面都有空格(根据所示模式)。
library(stringr)
as.numeric(str_extract(str1, "(?<=\\s)\\d+(?=\\s)"))
#[1] 200

数据

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接