0

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, e.g. -.

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

WCMC
  • 1,354
  • 3
  • 17
  • 30

1 Answers1

4

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

SymbolixAU
  • 23,954
  • 4
  • 56
  • 128