当您不确定要找什么时
到目前为止,您使用的是 str_detect(),当模式匹配时返回 TRUE,否则返回 FALSE。但正则表达式也非常擅长从大量文本中提取目标内容。为此,您可以使用 str_match() 函数。
接下来要认识的特殊字符是句点:"."。句点可以匹配任意字符,就像通配符一样。因此,如果您搜索例如 "...",就会匹配到任意 3 个字符——可以是字母、数字,甚至是空白符。
这很方便,除非您需要匹配实际的句号 "."。这种情况下:请用两个反斜杠对句点进行转义:"\\."。
本练习是课程的一部分
R 中级正则表达式
练习说明
- 不仅匹配
Saw 4,也要匹配其他续集。 - 匹配所有以
"K"开头的电影标题的前 4 个字符。 - 检测以实际句号
"."结尾的电影。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Here's an example pattern that will find the movie Saw 4
str_match(movie_titles, pattern = "Saw 4")
# Match all sequels of the movie "Saw"
str_match(movie_titles, pattern = "___")
# Match the letter K and three arbitrary characters
str_match(movie_titles, pattern = "^K___")
# Detect whether the movie titles end with a full stop
str_detect(movie_titles, pattern = "___$")