R,检查字符串中是否有特殊字符

WCM*_*CMC 0 r

如何使用 R 检查字符串是否至少包含以下字符之一:/\:*?"<>|。另外,我希望该字符串可以包含任何其他字符,例如-

实际上这些字符是 Windows 目录(文件夹)名称中不允许使用的字符。

Sym*_*xAU 5

定义要在字符串中查找的模式,然后使用grepl它来查找它们

pattern <- "/|:|\\?|<|>|\\|\\\\|\\*"

myStrings <- c("this/isastring", "this*isanotherstring", "athirdstring")

grepl(pattern, myStrings)
# [1] TRUE TRUE FALSE
Run Code Online (Sandbox Code Playgroud)

分解为pattern

如果是的话

pattern <- "/"
Run Code Online (Sandbox Code Playgroud)

这只会搜索“/”

竖线/竖线用作模式上的“OR”条件,因此

pattern <- "/|:"
Run Code Online (Sandbox Code Playgroud)

正在搜索“/”或“:”

搜索“|” 字符本身,您需要使用“\”对其进行转义

pattern <- "/|:|\\|"
Run Code Online (Sandbox Code Playgroud)

要搜索“”字符,您也需要对其进行转义(对于其他特殊字符也类似,?,*,...

pattern <- "/|:|\\?|<|>|\\|\\\\"
Run Code Online (Sandbox Code Playgroud)

参考: R中特殊字符的处理