擷取群組

R 中級 Regular Expressions

Angelo Zehr

Data Journalist

規則樣式

str_match(
  "payload: 'Adam, 5, 3', headers: 'Auth...'",
  pattern = "[A-Za-z]+, \\d+, \\d+"
)

Resulted in:

     [,1]        
[1,] "Adam, 5, 3"
R 中級 Regular Expressions

認識擷取群組

str_match(
  "payload: 'Adam, 5, 3', headers: 'Auth...'",
  pattern = "([A-Za-z]+), (\\d+), (\\d+)"
)

Results in:

     [,1]         [,2]   [,3] [,4]
[1,] "Adam, 5, 3" "Adam" "5"  "3"
R 中級 Regular Expressions

取代

str_replace(
  "payload: 'Adam, 5, 3', headers: 'Auth...'",
  pattern = "([A-Za-z]+), (\\d+), (\\d+)",
  replacement = "\\1 tried to log in \\2 times."
)

Returns:

"payload: 'Adam tried to log in 5 times.', headers: 'Auth...'"`
R 中級 Regular Expressions

字串分割

str_split(
  "a:b:c:d",
  pattern = ":",
  simplify = FALSE
)
[[1]]
[1] "a" "b" "c" "d"
str_split(
  "a:b:c:d",
  pattern = ":",
  simplify = TRUE
)
     [,1] [,2] [,3] [,4]
[1,] "a"  "b"  "c"  "d"
R 中級 Regular Expressions

一起來練習吧!

R 中級 Regular Expressions

Preparing Video For Download...