gpt4 book ai didi

regex - R中的动态正则表达式

转载 作者:行者123 更新时间:2023-12-04 01:59:50 26 4
gpt4 key购买 nike

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

最佳答案

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

关于regex - R中的动态正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16221899/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com