Regular Expressions
aka ‘regex’ and ‘regexp’
a sort of find-and-replace for nerds
one of the most powerful data tools I have ever learned
requires patience and lots of practice
grep()
and grepl()
are equivalent to ‘find’ in your favorite word processor
grep("find this", in.this.object)
sub()
and gsub()
are equivalent to ‘find and replace’
grep("find this", "replace with this", in.this.object)
regexpr()
provides more detailed info about the first match
gregexpr()
provides more detailed results about all matches
More examples here
Species<-c("petiolata", "verticillatus", "salicaria", "minor")
print(Species)
## [1] "petiolata" "verticillatus" "salicaria" "minor"
grep()
– returns cell addresses matching querygrep("a",Species)
## [1] 1 2 3
grepl()
– returns T/F associated withgrepl("a",Species)
## [1] TRUE TRUE TRUE FALSE
sub()
– replaces first match (in each cell)sub("l","L",Species)
## [1] "petioLata" "verticiLlatus" "saLicaria" "minor"
gsub()
– replaces all matchesgsub("l","L",Species)