#> 4 如今鸡腿是一道罕见的菜。a chicken #> 5 米饭常常盛在圆碗里。
与 str_extract() 一样,如果你想获得每个字符串的所有匹配,需要使用 str_match_all()。
练习
-
- 找出所有出现在“数字”后面的单词,比如“one”、“two”、“three”等。同时提取出数字和单词。
-
- 找出所有缩写形式。将撇号前后的部分分开。
替换匹配
str_replace() 和 str_replace_all() 允许你用新字符串替换匹配项。最简单的用法是用一个固定字符串替换某个模式:
x <- c("apple", "pear", "banana") str_replace(x, "[aeiou]", "-") #> [1] "-pple" "p-ar" "b-nana" str_replace_all(x, "[aeiou]", "-") #> [1] "-ppl-" "p--r" "b-n-n-"
使用 str_replace_all() 时,你可以通过提供一个命名向量来执行多个替换:
x <- c("1 house", "2 cars", "3 people") str_replace_all(x, c("1" = "one", "2" = "two", "3" = "three")) #> [1] "one house" "two cars" "three people"
除了用固定字符串替换,你还可以使用反向引用来插入匹配的组成部分。在下面的代码中,我交换了第二个和第三个单词的顺序:
sentences %>% str_replace("([^ ]+) ([^ ]+) ([^ ]+)", "\1 \3 \2") %>% head(5)
#> [1] "The canoe birch slid on the smooth planks." #> [2] "Glue sheet the to the dark blue background." #> [3] "It's to easy tell the depth of a well." #> [4] "These a days chicken leg is a rare dish." #> [5] "Rice often is served in round bowls."