當你不確定要找什麼時
到目前為止,你用了 str_detect(),當樣式比對成功會回傳 TRUE,否則回傳 FALSE。不過,規則運算式也非常適合從大量文字中擷取你要找的片段。你可以使用 str_match() 這個函式。
接下來要認識的特殊字元是句點:"."。句點可以比對任何字元,就像萬用字元一樣。所以,如果你搜尋 "...",就會找到連續 3 個字元——可以是英文字母、數字,甚至是空白字元。
這很方便,但如果你真的需要搜尋一個實際的句點 ".",那就得用兩個反斜線來跳脫它:"\\."。
本練習屬於課程
R 中級 Regular Expressions
練習說明
- 不只要比對到
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 = "___$")