Skip to content

Instantly share code, notes, and snippets.

@klmr
Created May 10, 2013 15:52
Show Gist options
  • Save klmr/5555335 to your computer and use it in GitHub Desktop.
Save klmr/5555335 to your computer and use it in GitHub Desktop.
Wrapper around `gregexpr` to find and extract substrings
rxmatches <- function (pattern, text) {
result <-
mapply(function (positions, t)
mapply(function (p, l)
if (p == -1) NULL else substr(t, p, p + l - 1),
positions,
attr(positions, 'match.length')),
gregexpr(pattern, text),
text)
# Sanitise to get rid of redundant singleton lists of NULL
lapply(result,
function (x)
if (is.null(x[[1]])) NULL else x)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment