grepl 與 grep(2)
你可以使用脫字號 ^ 和美元符號 $,分別比對字串開頭與結尾的位置。這能讓我們更接近只從電子郵件清單中比對出以「.edu」結尾的電子郵件。不過還可以加入更多元素,讓樣式更穩健:
@,因為有效的電子郵件一定包含 at 符號。.*,會比對任意字元(.)出現 0 次或多次(*)。點與星號都是中介字元。你可以用它們來比對 at 符號與電子郵件中「.edu」之間的任何字元。\\.edu$,用來在字串結尾比對電子郵件的「.edu」部分。\\這一段會「跳脫」點號:它告訴 R 你要把.視為實際字元。
本練習屬於課程
R 中級
練習說明
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# The emails vector has already been defined for you
emails <- c("[email protected]", "[email protected]", "[email protected]",
"invalid.edu", "[email protected]", "[email protected]")
# Use grepl() to match for .edu addresses more robustly
# Use grep() to match for .edu addresses more robustly, save result to hits
# Subset emails using hits