简体   繁体   中英

R, check if special character in string

How to use R to check if a string contains at least one of the following characters, /\\:*?"<>| . Also, I hope the string can contain any other characters, eg - .

Actually these characters are the ones not allowed for windows directory (folder) name.

Define the pattern(s) you want to find in the string, then use grepl to find them

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

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

grepl(pattern, myStrings)
# [1] TRUE TRUE FALSE

A break down of pattern :

if it were

pattern <- "/"

This would just search for "/"

The vertical bar/pipe is used as an 'OR' condition on the pattern, so

pattern <- "/|:"

is searching for either "/" OR "|"

To search for the "|" character itself, you need to escape it using "\\"

pattern <- "/|:|\\|"

And to search for the "\\" character, you need to escape that too (and similarly for other special characters, ?, *, ...

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

Reference: Dealing with special characters in R

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM