How to replace '\' with '/' using regex in Python [duplicate] - regex

This question already has answers here:
How to convert back-slashes to forward-slashes?
(9 answers)
Closed 4 years ago.
I tried this but did not work.
import re
s = "Ex\am\ple String"
replaced = re.sub("\", "/", s)
print replaced
Any suggestions?

Just use this code:
s = s.replace("\\", "/")
It replaces all the backslashes with the forward slash. The reason for the two backslashes is because you have to escape the other backslash.

Try it like this with \\\\:
import re
s = "Ex\am\ple String"
replaced = re.sub("\\\\", "/", s)
print replaced

You likely aren't using enough backslashes.
Backslash is often an escape character. Try commenting here using one \, then two \, you'll notice you only get one in the output here.
code version of what I just typed to show what I mean:
Backslash is often an escape character. Try commenting here using one \,
then two \\, you'll notice you only get one in the output here.
I wrote a similar code in R for when I cut and paste file locations
fileLoc = function(){
Rlocation = gsub( "\\\\","/",readClipboard())
return(Rlocation)
}
Notice it required 4 backslashes.
Try the following:
s = "Ex\am\ple String"
replaced = re.sub("\\\\", "/", s)

You have two problems: First, your string is not what you think it is, because '\a' is interpreted as an escape literal. To fix this, use a raw or regex string,
s = r"Ex\am\ple String"
Now you can do what you want using
replaced = re.sub(r"\\", "/", s)
Here, two \ are needed because re expect a single \ to be an escape character. Also, the r"\\" needs to be a raw string because Python more generally also interprets "\" as an escape character. To "escape the escape character" itself, you can do the double \ trick again, and so another way of doing it would be
replaced = re.sub("\\\\", "/", s)
Better method
Escaping and the re module aside, for simple replacements like this, you should use the str replace method,
replaced = s.replace("\\", "/")
("only" two \ needed because we are only using "bare" Python, not also re)

Related

Print on the screen the symbol \ as text [duplicate]

This question already has answers here:
using \ in a string as literal instead of an escape
(2 answers)
Closed 7 years ago.
I want the following printout to appear in the my screen when I run my code:
\begin{tabular}
\hline \\
For that, I am using the following command on my code:
std::cout<<"\begin{tabular}<< std::endl;
std::cout<<"\hline \\"<< std::endl;
And I'm getting the following compiler message (regarding the second line of code):
unknown escape sequence: '\h'
and the following incomplete printout:
egin{tabular}
hline\
Where in the first one the "\b" is missing and the first and last \ are missing for the second sentence.
The question is: does anyone know how I can print the \ symbol as text, such that it will get printed and not be interpreted as a command, etc?
The backslash forms escape sequences in C++. You have two options:
Double all the backslashes, a la "\\hline \\\\" (the backslash will escape itself, just as in TeX).
Use C++11 raw strings, which look like R"(\hline \\)" (the text is enclosed by the parens inside the quotes).
Just escape it wiht '\'. So if you want to print out '\' character you must do:
cout<<'\\'<<endl;
Use double backslash (\) if you would like to print \ as a character in your output, otherwise, single \ followed by some character has inherent meaning of some special character, e.g. \n for newline, \r for carriage return \t for tab etc
Double all the backslashes.
e.g.
std::cout<<"\\hline \\\\"<< std::endl;
backslash is an escape code in C++.
As in, below, the "\"escape sequence and n is escape code. Which means a newline character.
"hello\n"
so if you want to print \ as well, you need to escape it too.
"hello\\hi"

How to replace a symbol by a backslash in R?

Could you help me to replace a char by a backslash in R? My trial:
gsub("D","\\","1D2")
Thanks in advance
You need to re-escape the backslash because it needs to be escaped once as part of a normal R string (hence '\\' instead of '\'), and in addition it’s handled differently by gsub in a replacement pattern, so it needs to be escaped again. The following works:
gsub('D', '\\\\', '1D2')
# "1\\2"
The reason the result looks different from the desired output is that R doesn’t actually print the result, it prints an interpretable R string (note the surrounding quotation marks!). But if you use cat or message it’s printed correctly:
cat(gsub('D', '\\\\', '1D2'), '\n')
# 1\2
When inputting backslashes from the keyboard, always escape them:
gsub("D","\\\\","1D2")
#[1] "1\\2"
or,
gsub("D","\\","1D2", fixed=TRUE)
#[1] "1\\2"
or,
library(stringr)
str_replace("1D2","D","\\\\")
#[1] "1\\2"
Note: If you want something like "1\2" as output, I'm afraid you can't do that in R (at least in my knowledge). You can use forward slashes in path names to avoid this.
For more information, refer to this issue raised in R help: How to replace double backslash with single backslash in R.
gsub("\\p{S}", "\\\\", text, perl=TRUE);
\p{S} ... Match a character from the Unicode category symbol.

gsub("BLAH", "", "BLAH\WHAT") won't let x have a backslash? [duplicate]

This question already has answers here:
How to escape a backslash in R? [duplicate]
(2 answers)
Closed 8 years ago.
I'm doing some batch string clean up and a lot of the entries look like this:
"ABC\Company Co."
Which causes weird errors, and I can't seem to remove the backslash.
For example, try entering this into your console:
gsub("BLAH", "", "BLAH\WHAT")
and you get:
Error: '\W' is an unrecognized escape in character string starting ""BLAH\W"
I know that it's thinking \W is a command.. I'm actually suprised that gsub's 'interpreting' x, since x is just the string I want to sub out. I don't get why gsub cares what's actually in x, just that it should replace "BLAH" with "" within "BLAH\WHAT"...
The obvious solution would be to remove the \ from the string ahead of time.
gsub("\\", "", "BLAH\WHAT")
But then you get the exact same error message!
Thoughts? Thanks!
Use
gsub("\\\\", "", "BLAH\\WHAT")
which gives
[1] "BLAHWHAT"
To produce one backslash, you need to escape it using a \. Thus, "\\\\" produces two backslashes, which matches the two inside "BLAH\\WHAT".
See these related questions:
How to escape a backslash in R?
How to escape backslashes in R string

How to change "It's" to "It is" (without apostrophe) using str_replace?

I want to replace from Facebook's relationships string "It's complicated" to other text.
The line is like this:
$user->relationship = str_replace(array('single', 'It's complicated'), array('Soltero(a)', 'Es complicado'),$data['relationship_status']);
Using: 'It's complicated' , 'It&apos;s complicated' or 'It's complicated' ,
do not work.
Any suggestions?
Thanks a lot.
Regards.
If you want to use literal single quoted character ('), you have to escape them.
like:
$str = '\''; // single quote
You could try this.
$user->relationship = str_replace(array('single', 'It\'s complicated'), array('Soltero(a)', 'Es complicado'),$data['relationship_status']);
The PHP could not recognize the single literal quoted character (') without escape sequences character. Here is the explanation about it:
Strings literal
It's also happen for double literal quoted character (").

Double-escaping regex from inside a Groovy expression

Note: I had to simplify my actual use case to spare SO a lot of backstory. So if your first reaction to this question is: why would you ever do this, trust me, I just need to.
I'm trying to write a Groovy expression that replaces double-quotes (""") that appear in a string with single-quotes ("'").
// BEFORE: Replace my "double" quotes with 'single' quotes.
String toReplace = "Replace my \"double-quotes\" with 'single' quotes.";
// Wrong: compiler error
String replacerExpression = "toReplace.replace(""", "'");";
Binding binding = new Binding();
binding.setVariable("toReplace", toReplace);
GroovyShell shell = new GroovyShell(binding);
// AFTER: Replace my 'double' quotes with 'single' quotes.
String replacedString = (String)shell.evaluate(replacerExpression);
The problem is, I'm getting a compile error on the line where I assign replacerExpression:
Syntax error on token ""toReplace.replace("", { expected
I think it's because I need to escape the string that contains the double-quote character (""") but since it's a string-inside-a-string, I'm not sure how to properly escape it here. Any ideas?
You need to escape the quote within quotes in this line:
String replacerExpression = "toReplace.replace(""", "'");";
The string will be evaluated twice: once as a string literal, and once as a script. This means you have to escape it with a backslash, and escape the backslash too. Also, with the embedded quotes, it'll be much more readable if you use triple quotes.
Try this (in groovy):
String replacerExpression = """toReplace.replace("\\"", "'");""";
In Java, you're stuck with using backslashes to escape all the quotes and the embedded backslash:
String replacerExpression = "toReplace.replace(\"\\\"\", \"\'\");";
Triple-quotes work well, but one can also use single-quoted string to specify a double-quote, and a double-quoted string for a single-quote.
Consider this:
String toReplace = "Replace my \"double-quotes\" with 'single' quotes."
// key line:
String replacerExpression = """toReplace.replace('"', "'");"""
Binding binding = new Binding(); binding.setVariable("toReplace", toReplace)
GroovyShell shell = new GroovyShell(binding)
String replacedString = (String)shell.evaluate(replacerExpression)
That is, after the string literal evaluation, this is evaluated in the Groovy shell:
toReplace.replace('"', "'");
If that is too hard on the eyes, replace the "key line" above with another style (using slashy strings):
String ESC_DOUBLE_QUOTE = /'"'/
String ESC_SINGLE_QUOTE = /"'"/
String replacerExpression = """toReplace.replace(${ESC_DOUBLE_QUOTE}, ${ESC_SINGLE_QUOTE});"""
Please try to use regular expressions to solve this kind of problems, instead of messing your head to tackle the escaping of quotes.
I have put up a solution using groovy console. Please see if that helps.