如何在带有R的字符串中的货币字之前获取值?

时间:2018-03-15 03:52:08

标签: r string text

如果这是非常基本的话,请提前道歉!

我有以下字符串:

text <- "Odebrecht has admitted to paying $29 million in bribes to public officials in Peru between 2005 and 2014 in exchange for $12.5 billion in contracts."

如何获得“百万”和“十亿”之前的金额?

提前致谢!

1 个答案:

答案 0 :(得分:0)

这是一个stringr解决方案,使用外观和正则表达式。我匹配后跟\\S的非空格字符million和空格billion

text <- "Odebrecht has admitted to paying $29 million in bribes to public officials in Peru between 2005 and 2014 in exchange for $12.5 billion in contracts."

library(stringr)
text %>%
  str_extract_all("\\S*? (?=(million|billion))", simplify = TRUE) %>%
  str_trim()
#> [1] "$29"   "$12.5"

reprex package(v0.2.0)创建于2018-03-14。