只要before
和after
字符串不包含正则表达式专用的字符,以下代码即可工作:
before <- 'Name of your Manager (note "self" if you are the Manager)' #parentheses cause problem in regex
after <- 'CURRENT FOCUS'
pattern <- paste0(c('(?<=', before, ').*?(?=', after, ')'), collapse='')
ex <- regmatches(x, gregexpr(pattern, x, perl=TRUE))
R是否具有转义要在正则表达式中使用的字符串的功能?
最佳答案
使用\Q...\E
包围逐字模式:
# test data
before <- "A."
after <- ".Z"
x <- c("A.xyz.Z", "ABxyzYZ")
pattern <- sprintf('(?<=\\Q%s\\E).*?(?=\\Q%s\\E)', before, after)
这使:
> gregexpr(pattern, x, perl = TRUE) > 0
[1] TRUE FALSE