R 中級 Regular Expressions
Angelo Zehr
Data Journalist
| 字元類別 | 範例 |
|---|---|
\\d or [:digit:] |
0, 1, 2, 3,… |
\\w or [:word:] |
a, b, c…, 1, 2, 3…, _ |
[A-Za-z] or [:alpha:] |
A, B, C,…, a, b, c,… |
[aeiou] |
a、e、i、o 或 u |
\\s or [:space:] |
" "、Tab 或換行 |
str_match_all() |
結果 |
|---|---|
"Hi John_35", "\\d" |
"3"、"5" |
"Hi John_35", "\\w" |
"H"、"i"、"J"、"o"、"h"、"n"、"_"、"3"、"5" |
"Hi John_35", "[A-Za-z]" |
"H"、"i"、"J"、"o"、"h"、"n" |
"Hi John_35", "[aeiou]" |
"i"、"o" |
"Hi John_35", "\\s" |
" " |
| 語法 | 意義 |
|---|---|
\\w{2} |
正好重複 2 次 |
\\w{2,3} |
最少 2 次,最多 3 次 |
\\w{2,} |
最少 2 次,上限不限 |
\\w+ |
重複 1 次以上 |
\\w* |
重複 0、1 次或以上 |
| 原本 | 反向 |
|---|---|
\\d 比對數字 |
\\D 比對除了數字以外 |
\\w 比對單字字元 |
\\W 比對除了單字字元以外 |
\\s 比對空白 |
\\S 比對除了空白以外 |
[a-zA-Z] 比對字母 |
[^a-zA-Z] 比對除了字母以外 |
str_match_all("Toy Story 3", "[\\d\\s]")
結果:
[,1]
[1,] " "
[2,] " "
[3,] "3"
R 中級 Regular Expressions