R中的动态正则表达式

时间:2013-04-25 18:19:19

标签: regex r

只要beforeafter字符串没有正则表达式特有的字符,下面的代码就可以运行:

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是否有函数来转义要在正则表达式中使用的字符串?

3 个答案:

答案 0 :(得分:7)

在Perl中,有http://perldoc.perl.org/functions/quotemeta.html就是这么做的。如果说文档正确

  
    

返回EXPR的值,并将所有ASCII非“word”字符反斜杠。 (也就是说,所有不匹配的ASCII字符/ [A-Za-z_0-9] /将在返回的字符串中以反斜杠开头,而不管任何语言环境设置。)

  

然后你可以通过这样做来实现同样的目标:

quotemeta <- function(x) gsub("([^A-Za-z_0-9])", "\\\\\\1", x)

你的模式应该是:

pattern <- paste0(c('(?<=', quotemeta(before), ').*?(?=', quotemeta(after), ')'),
                  collapse='')

快速健全检查:

a <- "he'l(lo)"
grepl(a, a)
# [1] FALSE
grepl(quotemeta(a), a)
# [1] TRUE

答案 1 :(得分:5)

使用\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

答案 2 :(得分:1)

dnagirl,这样的函数存在并且是glob2rx

a <- "he'l(lo)"
tt <- glob2rx(a)
# [1] "^he'l\\(lo)$"

before <- 'Name of your Manager (note "self" if you are the Manager)'
tt <- glob2rx(before)
# [1] "^Name of your Manager \\(note \"self\" if you are the Manager)$"

您可以通过执行以下操作从字符串中删除“^”和“$”:

substr(tt, 2, nchar(tt)-1)
# [1] "he'l\\(lo)"