How can I use back references with `grep` in R?

与世无争的帅哥 提交于 2019-12-03 09:51:11

问题


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:

  1. You have to wrap the pattern inside ".*(pattern).*)" so that the substitution occurs on the entire string.
  2. Rather than returning NA for non-matched strings, 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?


回答1:


The stringr package has a function exactly for this purpose:

library(stringr)
x <- c("May, 1, 2011", "30 June 2011", "June 2012")
str_extract(x, "May|^June")
# [1] "May"  NA     "June"

It's a fairly thin wrapper around regexpr, but stringr generally makes string handling easier by being more consistent than base R functions.




回答2:


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"



回答3:


The gsubfn package is more general than the grep and regexpr functions and has ways for you to return the backrefrences, see the strapply function.



来源:https://stackoverflow.com/questions/6199350/how-can-i-use-back-references-with-grep-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!