U_REGEX_INVALID_CAPTURE_GROUP_NAME error occurs when trying to escape regex characters on Windows only

被刻印的时光 ゝ 提交于 2019-12-01 21:59:18

Use a simple str_replace_all to escape all the special regex metacharacters:

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:

  • The "[{\\[\\]()|?$^*+.\\\\] (actually, "[{\[\]()|?$^*+.\\]) will match any single char, either {, [, ], (, ), |, ?, $, ^, *, +, . or \
  • The "\\$0" replacement will change each of the chars into \ + the same char (the $0 is the backreference to the whole match value).
  • I do not think you need to add ] here since outside a character class it is not a special character if there is no paired opening [ in front.
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!