I am looking for an elegant way of returning back references using regular expressions in R. Le me explain:
Let’s say I want to find strings that start with a month name:
x <- c("May, 1, 2011", "30 June 2011")
grep("May|^June", x, value=TRUE)
[1] "May, 1, 2011"
This works, but I really want to isolate the month (i.e. “May”, not the entire matched string.
So, one can use gsub to return the back reference using the substitute parameter. But this has two problems:
- You have to wrap the pattern inside “.*(pattern).*)” so that the substitution occurs on the entire string.
- Rather than returning NA for non-matched strings,
gsubreturns the original string. This is clearly not what I desire:
The code and results:
gsub(".*(^May|^June).*", "\\1", x)
[1] "May" "30 June 2011"
I could probably code a workaround by doing all kinds of additional checks, but this quickly becomes very messy.
To be crystal clear, the desired results should be:
[1] "May" NA
Is there an easy way of achieving this?
The
stringrpackage has a function exactly for this purpose:It’s a fairly thin wrapper around
regexpr, butstringrgenerally makes string handling easier by being more consistent than base R functions.