S A
S A

Reputation: 23

How to test whether \ is in a string?

I am working with the following string:

Potent_Abb <- "GR\xdcNE"

I want to test whether the string contains the "\" in it. So it produces a boolean (True or False) as the output.

Any help you could offer would be appreciated.

Upvotes: 2

Views: 401

Answers (2)

deepseefan
deepseefan

Reputation: 3791

A quote from Handling Strings with R

Not all metacharacters become literal characters when they appear inside a character set. The exceptions are the closing bracket ], the dash -, the caret ^, and the backslash \.

An answer to your question "How can I test a backslash(\) is in a string?" can be found R for Data Science:

...If \ is used as an escape character in regular expressions, how do you match a literal \? Well you need to escape it, creating the regular expression \\. To create that regular expression, you need to use a string, which also needs to escape \. That means to match a literal \ you need to write \\\\ — you need four backslashes to match one!

An example using your string using stringr:

library(stringr)

Potent_Abb <- "GR\xdcNE"
writeLines(Potent_Abb, con = stdout()) # cat(Potent_Abb)
#GR�NE
# to detect if the string has a backslash
str_detect(Potent_Abb, "\\\\")
# FALSE

#Let's add a backslash literal at the end 
# we need to escape the '\` using a '\` to represent it as a literal, hence `\\`
Potent_Abb <- "GR\xdcNE\\"
writeLines(Potent_Abb, con = stdout()) # cat(Potent_Abb)
#GR�NE\

str_detect(Potent_Abb, "\\\\")
# TRUE

Hope that adds something somewhere if not a future reference to myself.

Upvotes: 2

user10191355
user10191355

Reputation:

You can use iconv to replace ASCII characters with some other character, and then match that character instead:

Potent_Abb <- "GR\xdcNE"

grepl("#", iconv(Potent_Abb, "ASCII", sub = "#"))

# [1] TRUE

Upvotes: 1

Related Questions