[英]How to precisely check for illegal characters of file paths?
我正在開發一個 Shiny 應用程序,它為每個用戶及其每個實驗生成文件夾和子文件夾。
我希望確保用戶名和實驗名都不包含任何非法字符。
我用我知道的每個非法字符定義了一個字符向量,但是,有可能出現人為錯誤。 有沒有更精確的方法來做到這一點?
dir <- "~/home/my_app_data"
usr <- "john"
exp <- "explosion`s"
path <- paste(dir, usr, exp, sep = "/")
illegal <- c(" ", ",", "`")
if (any(illegal %in% (strsplit(x = path, split = "") %>% unlist))) {
stop( "Illegal characters used")
} else {
dir.create(path, recursive = T)
}
使用grepl
。 pattern="\\W"
查找不包括下划線"_"
的非單詞字符。
FUN <- function(x) {
if (grepl("\\W", x)) stop(sprintf("Illegal characters used in '%s'", x)) else x
}
FUN(usr)
# [1] "john"
FUN(exp)
# Error in FUN(exp) : Illegal characters used in 'explosion`s'
lapply(c(usr, exp), FUN)
# Error in FUN(X[[i]], ...) : Illegal characters used in 'explosion`s'
FUN("john123")
# [1] "john123"
FUN("john_123")
# [1] "john_123"
(當然你想定義你的自定義else
條件。)
dir <- "~/home/my_app_data"
usr <- "john"
exp <- "explosion`s"
path <- paste(dir, usr, exp, sep = "/")
應該防止大多數錯誤:
if(!(identical(gsub(
"[^[:alnum:]]+",
"_",
iconv(exp, from = "ascii", "utf-8")
), exp))) {
stop("Illegal characters used")
} else {
dir.create(path, recursive = TRUE)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.