Expressões regulares

R intermediário

Filip Schouwenaars

DataCamp Instructor

Expressões regulares

  • Sequência de (meta)caracteres
  • Existência de padrões
  • Substituição de padrões
  • Extração de padrões
  • grep(), grepl()
  • sub(), gsub()
R intermediário

grepl()

animals <- c("cat", "moose", "impala", "ant", "kiwi")
grepl(pattern = <regex>, x = <string>)
grepl(pattern = "a", x = animals)
TRUE FALSE  TRUE  TRUE FALSE
R intermediário

grepl()

grepl(pattern = "^a", x = animals)
FALSE FALSE FALSE  TRUE FALSE
grepl(pattern = "a$", x = animals)
FALSE FALSE  TRUE FALSE FALSE
?regex
R intermediário

grep()

animals <- c("cat", "moose", "impala", "ant", "kiwi")
grepl(pattern = "a", x = animals)
TRUE FALSE  TRUE  TRUE FALSE
grep(pattern = "a", x = animals)
1 3 4
R intermediário

grep()

which(grepl(pattern = "a", x = animals))
1 3 4
grep(pattern = "^a", x = animals)
4
R intermediário

sub(), gsub()

animals <- c("cat", "moose", "impala", "ant", "kiwi")
sub(pattern = <regex>, replacement = <str>, x = <str>)
sub(pattern = "a", replacement = "o", x = animals)
"cot"    "moose"  "impola" "ont"    "kiwi"
gsub(pattern = "a", replacement = "o", x = animals)
"cot"    "moose"  "impolo" "ont"    "kiwi"
R intermediário

sub(), gsub()

animals <- c("cat", "moose", "impala", "ant", "kiwi")
sub(pattern = "a", replacement = "o", x = animals)
"cot"    "moose"  "impola" "ont"    "kiwi" 
gsub(pattern = "a", replacement = "o", x = animals)
"cot"    "moose"  "impolo" "ont"    "kiwi"
R intermediário

sub(), gsub()

gsub(pattern = "a|i", replacement = "_", x = animals)
"c_t"    "moose"  "_mp_l_" "_nt"    "k_w_"
gsub(pattern = "a|i|o", replacement = "_", x = animals)
"c_t"    "m__se"  "_mp_l_" "_nt"    "k_w_"
R intermediário

Vamos praticar!

R intermediário

Preparing Video For Download...