str_match用法與str_extract用法基本上一樣,差別在於str_extract回傳的是一個list,str_match回傳的是一個陣列
基本語法
str_match(dataset$string, 查找的字元或字串模式)
str_match_all(dataset$string, 查找的字元或字串模式)
有一點要注意一下
- 小寫與大寫判斷為不同字元,需要完全確定大小寫
stringr_df <- tibble(
weekday = c("Sunday 4", "Monday", "Tuesday", "Wednesday",
"Thursday 77", "Friday", "Saturday 335")
)
# 輸出結果
r$> stringr_df
# A tibble: 7 x 1
weekday
<chr>
1 Sunday 4
2 Monday
3 Tuesday
4 Wednesday
5 Thursday 77
6 Friday
7 Saturday 335
查找數字與全部,查找結果僅以第一個結果位置作為返回條件,若要返回全部數字,需尾端加上" + ",返回時以陣列型式傳回
# 查找數字
str_match(stringr_df$weekday, "\\d")
# 輸出結果
r$> str_match(stringr_df$weekday, "\\d")
[,1]
[1,] "4"
[2,] NA
[3,] NA
[4,] NA
[5,] "7"
[6,] NA
[7,] "3"
# 查找全部數字
str_match_all(stringr_df$weekday, "\\d")
# 輸出結果
r$> str_match_all(stringr_df$weekday, "\\d")
[[1]]
[,1]
[1,] "4"
[[2]]
[,1]
[[3]]
[,1]
[[4]]
[,1]
[[5]]
[,1]
[1,] "7"
[2,] "7"
[[6]]
[,1]
[[7]]
[,1]
[1,] "3"
[2,] "3"
[3,] "5"
沒有留言:
張貼留言