#> [3] "判断井的深浅很容易。" #> [4] "如今鸡腿是一道罕见的菜。" #> [5] "米饭常常盛在圆碗里。" #> [6] "柠檬汁能做出美味的潘趣酒。"
假设我们想找出所有包含颜色的句子。我们先创建一个由颜色名称组成的向量,然后将其转换为一个正则表达式:
colors <- c( "red", "orange", "yellow", "green", "blue", "purple" ) color_match <- str_c(colors, collapse = "|") color_match #> [1] "red|orange|yellow|green|blue|purple"
现在我们可以筛选出包含颜色的句子,然后提取出颜色以确定是哪一种:
has_color <- str_subset(sentences, color_match) matches <- str_extract(has_color, color_match) head(matches) #> [1] "blue" "blue" "red" "red" "red" "blue"
注意 str_extract() 只提取第一个匹配项。通过先筛选出所有有多个匹配项的句子,我们可以最容易地看到这一点:
more <- sentences[str_count(sentences, color_match) > 1] str_view_all(more, color_match) str_extract(more, color_match) #> [1] "blue" "green" "orange"
这是 stringr 函数的一种常见模式,因为只处理单个匹配项可以使用简单得多的数据结构。要获取所有匹配项,请使用 str_extract_all()。它返回一个列表:
str_extract_all(more, color_match) #> [[1]] #> [1] "blue" "red"