比對所有擷取群組
在這個練習中,你會使用名為 top_10 的文字檔,其中存有電影名稱及其名次。這是一段多行文字,使用 \\n 代表換行。你將使用 str_split() 函式把這段文字切成多行。
新建立的一列矩陣 top_10_lines 會包含 10 行,且都有相同的結構:先是電影的名次,接著一個點與一個空白,然後是電影標題。本題會用 str_match() 與兩個擷取群組 (),把這兩項資訊從純文字中擷取出來,整理成表格形式。
本練習屬於課程
R 中級 Regular Expressions
練習說明
- 使用
str_split()把文字切成各行,並啟用simplify以輸出字元矩陣。 - 先熟悉每一行的結構,其中包含電影的名次與標題。
- 在
str_match()函式中使用擷取群組,擷取電影的名次與標題。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Split the input by line break and enable simplify
top_10_lines <- str_split(
top_10,
pattern = "___",
simplify = ___
)
# Inspect the first three lines and analyze their form
___[1:3]
# Add to the pattern two capturing groups that match rank and title
str_match(
top_10_lines,
pattern = "___\\. ___"
)