0

I have a variable named full.path. And I am checking if the string contained in it is having certain special character or not.

From my code below, I am trying to grep some special character. As the characters are not there, still the output that I get is true.

Could someone explain and help. Thanks in advance.

full.path <- "/home/xyz"

#This returns TRUE :(
grepl("[?.,;:'-_+=()!@#$%^&*|~`{}]", full.path)

IamGroot
  • 15
  • 5
  • 1
    `grepl("[?.,;:'-_+=()!@#$%^&*|~\`{}]", full.path, fixed = TRUE)` – Ronak Shah Jul 31 '19 at 01:19
  • 1
    @RonakShah: the dupe doesn't actually explain the specific issue here. The character class `[]` contains `-`, which creates a range. You have to have `-` as the first char in the character class to avoid creating a range, so `grepl("[-?.,;:'_+=()!@#$%^&*|~\`{}]", full.path)` should work as expected. Use https://regexr.com/ to figure out issues like this. – Marius Jul 31 '19 at 01:24
  • @Marius okay..I have reopened the question. I marked it because I thought OP would get expected answer if they escape all the special characters in the regex or add `fixed = TRUE` as explained in the link. – Ronak Shah Jul 31 '19 at 01:28
  • Yep, I guess it depends whether they want to match literal `[` or not, I assumed they were trying to use a character class and not match `[`. – Marius Jul 31 '19 at 01:33

1 Answers1

0

By plugging this regex into https://regexr.com/ I was able to spot the issue: if you have - in a character class, you will create a range. The range from ' to _ happens to include uppercase letters, so you get spurious matches.

To avoid this behaviour, you can put - first in the character class, which is how you signal you want to actually match - and not a range:

> grepl("[-?.,;:'_+=()!@#$%^&*|~`{}]", full.path)
[1] FALSE
Marius
  • 58,213
  • 16
  • 107
  • 105
  • Thanks @Marius. You understood and provided the correct solution. That link isn't opening though; may be site down. I'll check it later. Thanks again. :) – IamGroot Jul 31 '19 at 06:09
  • There are a few similar sites that explain regular expressions that you enter - you can google "regex explainer" or something to find one that's working for you. – Marius Jul 31 '19 at 06:11