這個或那個
搜尋一個單字很容易,對吧?但如果要精準搜尋兩或三個單字,就不是用傳統的「Control + F」就能辦到的。不過使用規則表示式,你就能定義出達成此目的的搜尋樣式。你可以用 str_view() 來查看你的規則表示式會匹配哪些內容。
當你用豎線運算子 | 連接多個單字時,會同時匹配在豎線前後的選項。而且不只兩個,你也可以用兩個豎線連接三個選項,例如 Hello Anna|Berta|Colin。
此外,你也可以用括號把特定的單字群組起來。例如搜尋 Hello (Anna|Berta|Colin),其結果會和上面的樣式不同。請試試看兩種作法,並比較結果。
本練習屬於課程
R 中級 Regular Expressions
練習說明
- 建立一個樣式,搜尋以
"Finding "開頭,且後面接著"Nemo"、"Harmony"或"Dory"的電影名稱。 - 接著建立相同的樣式,但把這三種可能性用括號
()包起來,以比較結果。 - 在兩個樣式中,選出能完整匹配
"Finding Nemo"、"Finding Harmony"、"Finding Dory"這三個片名的那一個,並將它傳入第三個str_match()呼叫。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Append the three options: Match Nemo, Harmony or Dory
str_view(lines, pattern = "Finding ___")
# Wrap the three options in parentheses and compare the results
str_view(lines, pattern = "Finding ___")
# Use the pattern from above that matched the whole movie names
str_match(lines, pattern = "Finding ___")