# NOT RUN {
library(nc)
named.subject.vec <- c(
ten="chr10:213,054,000-213,055,000",
M="chrM:111,000",
one="chr1:110-111 chr2:220-222") # two possible matches.
## Find the first match in each element of the subject character
## vector. Named argument values are used to create capture groups
## in the generated regex, and argument names become column names in
## the result.
(dt.chr.cols <- capture_first_vec(
named.subject.vec,
chrom="chr.*?",
":",
chromStart="[0-9,]+"))
## Even when no type conversion functions are specified, the result
## is always a data.table:
str(dt.chr.cols)
## Conversion functions are used to convert the previously named
## group, and patterns may be saved in lists for re-use.
keep.digits <- function(x)as.integer(gsub("[^0-9]", "", x))
int.pattern <- list("[0-9,]+", keep.digits)
range.pattern <- list(
chrom="chr.*?",
":",
chromStart=int.pattern,
list( # un-named list becomes non-capturing group.
"-",
chromEnd=int.pattern
), "?") # chromEnd is optional.
(dt.int.cols <- capture_first_vec(
named.subject.vec, range.pattern))
## Conversion functions used to create non-char columns.
str(dt.int.cols)
## NA used to indicate no match or missing subject.
na.vec <- c(
nomatch="this will not match",
missing=NA, # neither will this.
named.subject.vec)
capture_first_vec(na.vec, range.pattern, nomatch.error=FALSE)
## alternate regex engine, but this example with emoji only works
## with recent versions of ICU.
if(requireNamespace("stringi") && stringi::stri_info()$ICU.version >= 59){
capture_first_vec(
"foo a\U0001F60E# bar",
before=".*?",
emoji="\\p{EMOJI_Presentation}",
after=".*",
engine="ICU")
}
# }
Run the code above in your browser using DataLab