English · PDF 237
请注意,匹配结果永远不会重叠。例如,在 "abababa" 中,模式 "aba" 会匹配多少次?正则表达式给出的答案是两次,而不是三次:
str_count("abababa", "aba") #> [1] 2 str_view_all("abababa", "aba")
注意这里使用了 str_view_all()。你很快就会了解到,许多 stringr 函数都是成对出现的:一个函数处理单个匹配,另一个函数处理所有匹配。后一个函数会带有 _all 后缀。
要提取匹配结果的实际文本,可以使用 str_extract()。为了演示它的用法,我们需要一个更复杂的示例。我将使用 哈佛句子,它们最初是为测试 VOIP 系统而设计的,但也很适合用来练习正则表达式。这些句子包含在 stringr::sentences 中:
length(sentences) #> [1] 720 head(sentences) #> [1] "The birch canoe slid on the smooth planks." #> [2] "Glue the sheet to the dark blue background."