Learning how to extract parts of a string

[This article was first published on Maëlle's R blog on Maëlle Salmon's personal website, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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:

  1. Removing the final period, and the first words.
sub("My name is ", "", sub(".$", "", sentences))
#> [1] "Moomin"       "Little My"    "Snork Maiden"
  1. 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. 😁


  1. Learning how to add regex to code search on GitHub was well worth the small effort. ↩︎

To leave a comment for the author, please follow the link and comment on their blog: Maëlle's R blog on Maëlle Salmon's personal website.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)