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.

5
  • something like myStr <- "this/string"; grepl("[[:punct:]]", myStr) ? Commented Jul 13, 2017 at 1:46
  • @SymbolixAU, no because grepl("[[:punct:]]", "-") is true. Commented Jul 13, 2017 at 1:46
  • just make your pattern a bit more explicit: myStr <- "thisstring"; grepl("/|:|\\?|<|>|\\|\\\\|\\*", myStr) Commented Jul 13, 2017 at 1:49
  • @SymbolixAU Why not post that as an answer? Akrun is asleep right now, go on! Commented Jul 13, 2017 at 1:55
  • @TimBiegeleisen - ha - yep, just tidying it up :) Commented Jul 13, 2017 at 1:57

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.