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:
gsub
returns 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?
Back-references are specified with backslash and a single digit (e.g. ' \1 '). The part of the regular expression they refer to is called a subexpression, and is designated with parentheses.
The grep R function returns the indices of vector elements that contain the character “a” (i.e. the second and the fourth element). The grepl function, in contrast, returns a logical vector indicating whether a match was found (i.e. TRUE) or not (i.e. FALSE).
17.4 grepl() grepl() returns a logical vector indicating which element of a character vector contains the match. For example, suppose we want to know which states in the United States begin with word “New”. Here, we can see that grepl() returns a logical vector that can be used to subset the original state.name vector.
The backreference \1 (backslash one) references the first capturing group. \1 matches the exact same text that was matched by the first capturing group. The / before it is a literal character. It is simply the forward slash in the closing HTML tag that we are trying to match.
regexpr
is similar to grep
, but returns the position and length of the (first) match in each string:
> x <- c("May, 1, 2011", "30 June 2011", "June 2012")
> m <- regexpr("May|^June", x)
> m
[1] 1 -1 1
attr(,"match.length")
[1] 3 -1 4
This means that the first string had a match of length 3 staring at position 1, the second string had no match, and the third string had a match of length 4 at position 1.
To extract the matches, you could use something like:
> m[m < 0] = NA
> substr(x, m, m + attr(m, "match.length") - 1)
[1] "May" NA "June"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With