最近,我实现了一个函数,将可解释为regex的字符转义到我的R包'rNOMADS‘的系统调用中
SanitizeWGrib2Inputs <- function(check.strs) {
#Escape regex characters before inputting to wgrib2
#INPUTS
# CHECK.STRS - Strings possibly containing regex metacharacters
#OUTPUTS
# CHECKED.STRS - Strings with metacharacters appropriately escaped
meta.chars <- paste0("\\", c("(", ")", ".", "+", "*", "^", "$", "?", "[", "]", "|"))
for(k in 1:length(meta.chars)) {
check.strs <- stringr::str_replace(check.strs, meta.chars[k], paste0("\\\\", meta.chars[k]))
}
checked.strs <- check.strs
return(checked.strs)
}我在我的包文档中包括了一个例子:
check.strs <- c("frank", "je.rry", "har\\old", "Johnny Ca$h")
checked.strs <- SanitizeWGrib2Inputs(check.strs) 这在我的ubuntu机器上很好,并且通过了CRAN检查。然而,当我把这个包上传到CRAN时,他们的窗口检查器说:
> check.strs <- c("frank", "je.rry", "har\\old", "Johnny Ca$h")
> checked.strs <- SanitizeWGrib2Inputs(check.strs) Error in stri_replace_first_regex(string, pattern, fix_replacement(replacement), : Invalid capture group name. (U_REGEX_INVALID_CAPTURE_GROUP_NAME) Calls: SanitizeWGrib2Inputs -> <Anonymous> -> stri_replace_first_regex -> .Call Execution halted
** running examples for arch 'x64' ... ERROR Running examples in 'rNOMADS-Ex.R' failed The error most likely occurred in:
> base::assign(".ptime", proc.time(), pos = "CheckExEnv")
> ### Name: SanitizeWGrib2Inputs
> ### Title: Make sure regex metacharacters are properly escaped
> ### Aliases: SanitizeWGrib2Inputs
> ### Keywords: internal
>
> ### ** Examples
>
>
> check.strs <- c("frank", "je.rry", "har\\old", "Johnny Ca$h")
> checked.strs <- SanitizeWGrib2Inputs(check.strs) Error in stri_replace_first_regex(string, pattern, fix_replacement(replacement), : Invalid capture group name. (U_REGEX_INVALID_CAPTURE_GROUP_NAME) Calls: SanitizeWGrib2Inputs -> <Anonymous> -> stri_replace_first_regex -> .Call Execution halted我在我的Windows分区上验证了这个行为。这件事的工作是什么?
发布于 2017-03-24 14:02:56
使用一个简单的str_replace_all来转义所有特殊的regex元字符:
SanitizeWGrib2Inputs <- function(check.strs) {
return(str_replace_all(check.strs, "[{\\[()|?$^*+.\\\\]", "\\$0"))
}
check.strs <- c("frank", "je.rry", "har\\old", "Johnny Ca$h")
checked.strs <- SanitizeWGrib2Inputs(check.strs)
checked.strs
## => [1] "frank" "je\\.rry" "har\\\\old" "Johnny Ca\\$h"Notes
"[{\\[\\]()|?$^*+.\\\\] (实际上,"[{\[\]()|?$^*+.\\])将匹配任何单个字符,无论是{、[、]、(、)、|、?、$、^、*、+、.或\"\\$0"替换将将每个字符更改为\ +相同的字符( $0是对整个匹配值的反向引用)。],因为在字符类之外,如果前面没有对开的[,它不是一个特殊的字符。https://stackoverflow.com/questions/43001027
复制相似问题