隔离文本中的特定数值

Isolating specific numeric values in text

我有大量文本要在各种属性的文本 csv 文件上进行搜索,以查找属性的实际平方米数值。例如:

string <- "This is a wonderful 120 sqm flat with a stunning view"

我知道我可以使用以下方法提取数值:

sqm <- as.numeric(gsub("\D", "", string)) 

其中 return 是“120”的数字向量,它应该是这样。但是,我想知道是否有更复杂的方法来实现这一点,因为文本中可能有其他不相关的数值?

有什么方法可以搜索 'sqm' 和 return 前面的数字吗?非常感谢任何评论。

我相信这个正则表达式前瞻应该有效:

library(stringr)
##
string <- "This is a wonderful 120 sqm flat with a stunning view"
re <- "((\d+)(?=\s?sqm))"
##
R> str_extract(string, perl(re))
[1] "120"