r - 从 R 中的字符向量中提取数字和下一个字符串

标签 r regex stringr

我正在尝试解决问题。我有一个文本向量,我想从中提取数字和下一个字符(包括空格)。我正在使用 R 的 stringr 包,但我似乎找不到解决我的问题的好方法。我将感谢您的帮助/反馈。

library(tidyverse)
library(stringr)

my_text <- "This is my example vector. I have 15 oranges in the fridge, 12 apples in the room, 1 mother in my family, 1 father in my family, 12 siblings that live on 3 continents, and 45 randomthingsinmyhouse that I dont use"

# I would like to get the following information from my_text

"15 oranges" "12 apples" "1 mother" "1 father" "12 siblings" "45 randomthingsinmyouse"

我尝试过使用 str_extract_all(my_text, "\\\d+") 但显然只能获取数字。

str_extract_all(my_text, "\\d+")

# "15" "12" "1" "1" "12" "45"

我尝试在 stringr 包帮助页面 ( https://stringr.tidyverse.org/articles/regular-expressions.html ) 上使用不同的正则表达式模式,但我似乎找不到适合我的问题的模式。另外,数字后面的文字可以是随机的——我可以用鸡、房子等代替苹果和橙子。关于如何解决这个问题有什么建议吗?

非常感谢

最佳答案

使用该模式匹配一​​个或多个数字 (\\d+),后跟一个或多个空格 (\\s+) 和单词 (\\w+)

library(stringr)
str_extract_all(my_text, "\\d+\\s+\\w+")[[1]]

关于r - 从 R 中的字符向量中提取数字和下一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70339090/

相关文章:

r - ggsave png 尺寸较大时出现错误

r - 将顶点大小与 igraph 中的标签大小匹配

javascript - 具有特定首字母缩写的两个单词的出现 MongoDB

Javascript:如何使用正则表达式从字符串中提取多个值?

regex - 使用 Stringr 从字符串中删除多个字符

r - ggplot 两组的散点图,具有 X 和 Y 误差条的叠加平均值

r - 在 R 中从头开始计算自相关函数

java - matcher.find() 有什么问题?

r - 根据 r 中的最后一个单词对字符串进行排序

r - 错误 "the condition has length > 1 and only the first element will be used"是什么意思?