This week I took time to re-read The Programmer’s Brain by Felienne Hermans. Among the many gems one idea that stuck with me is that not learning how to do something and looking it up every time will make you less efficient. Therefore I starting feeling bad about one particular thing I never get done on my own: extracting parts of a string, even in simple cases.
Avoidance tactics
For instance, how do you extract names from the following templated sentences?
sentences <- c(
"My name is Moomin.",
"My name is Little My.",
"My name is Snork Maiden."
)
I would use either one of these two tactics:
- Removing the final period, and the first words.
- Looking up the regex syntax online (maybe even dutifully reading the stringr cheatsheet) or via a LLM. This could get me code calling stringr:
stringr::str_extract(sentences, "My name is (.*).", group = 1)
#> [1] "Moomin" "Little My" "Snork Maiden"
# Look arounds
stringr::str_extract(sentences, pattern = '(?<=My name is ).+(?=\\.)')
#> [1] "Moomin" "Little My" "Snork Maiden"
Or some base R code:
regmatches(
sentences,
regexpr("(?<=My name is ).+(?=\\.)", sentences, perl = TRUE)
)
#> [1] "Moomin" "Little My" "Snork Maiden"
My problems
Really I had two problems preventing me from being really autonomous:
- Not knowing enough regex.
- Not knowing where to put the regex, for whatever reason I felt I had to choose between adding a dependency on stringr or using the complicated two-step regexpr/regmatches syntax.
Solutions
To solve the first problem (lack of regex knowledge), I need to be more intentional about remembering the look-arounds syntax for instance, or what a group is.
What solved my second problem (thinking I had to choose between a dependency or code distateful to me) was a very simple tip by my rOpenSci colleague Jeroen Ooms: using sub()! The code below replaces the sentences with the names (capture groups) in them.
sub("My name is (.*).", "\\1", sentences)
#> [1] "Moomin" "Little My" "Snork Maiden"
This is code he seems to use quite often1.
What was especially great about this tip, beside its timing when I was reading the book, is that it made me “get” groups more easily. The group is what’s between parentheses, it’s not more complicated than that (at least I don’t need to know more right now).
Conclusion
I will try to keep mindful of not being too lazy to learn some things when I can actually learn them. And now I know that I can use something else than stringr or the not so easy base R syntax with regmatches(): a simple call to sub()! Watch me win seconds every time I have to extract parts of a string. 😁
-
Learning how to add regex to code search on GitHub was well worth the small effort. ↩︎