【问题标题】:dynamic regex in RR中的动态正则表达式
【发布时间】:2013-04-25 18:19:18
【问题描述】:

只要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 是否具有转义正则表达式中使用的字符串的功能?

【问题讨论】:

    标签: regex r


    【解决方案1】:

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

    返回 EXPR 的值,所有 ASCII 非“单词”字符都加反斜杠。 (也就是说,所有不匹配 /[A-Za-z_0-9]/ 的 ASCII 字符将在返回的字符串中以反斜杠开头,无论任何区域设置如何。)

    那么你可以通过这样做来达到同样的效果:

    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
    

    【讨论】:

    • 完美!我想它不是核心功能,因为 R 通常不用于文本处理。
    【解决方案2】:

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

    【讨论】:

    • 更好!我不知道\Q...\E。我可以看到它在很多地方都能派上用场。
    • 这很方便!如果您的正则表达式不需要perl = TRUE,则不需要\Q...\E 才能工作。
    【解决方案3】:

    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)"
    

    【讨论】:

    • 我在发布答案之前看到了glob2rx。我不认为这是任务的功能,例如尝试glob2rx(".*")。
    • @flodel,我知道它的局限性。大多数时候它对我有用。我在这里发帖的唯一原因是因为this Ricardo's post,他的问题似乎与这个问题完全相同。我被要求在此处发表我的评论作为答案。
    猜你喜欢
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    相关资源
    最近更新 更多