String.Replaceall Single Backslashes With Double Backslashes

String.replaceAll single backslashes with double backslashes

The String#replaceAll() interprets the argument as a regular expression. The \ is an escape character in both String and regex. You need to double-escape it for regex:

string.replaceAll("\\\\", "\\\\\\\\");

But you don't necessarily need regex for this, simply because you want an exact character-by-character replacement and you don't need patterns here. So String#replace() should suffice:

string.replace("\\", "\\\\");

Update: as per the comments, you appear to want to use the string in JavaScript context. You'd perhaps better use StringEscapeUtils#escapeEcmaScript() instead to cover more characters.

Java replaceAll: Cannot replace string with backslash

replace will work for you, replaceAll uses regex and \\ is a prefix for special characters, like \\s is white-space, \\. is any character, etc.

String test = "paloalto\\paloalto\\";
test = test.replace("paloalto\\", "sanhose\\");
System.out.println(test);

For replaceAll you can use the result of Pattern.quote as the first argument and the result of Matcher.quoteReplacement as the second:

test = test.replaceAll(Pattern.quote("paloalto\\"), Matcher.quoteReplacement("sanjose\\"));

Documentation.

How to replace Backslash '\' with double Backslash in Dart?

The problem is that the string string does not contain any \

It would either need to be

String string = r"back\slash back\slash back\slash back\slash";

or

String string = "back\\slash back\\slash back\\slash back\\slash";

In your example there also is no need for RegExp.
Just

String replaced = string.replaceAll(r'\', r'\\');

would do as well.

python replace single backslash with double backslash

No need to use str.replace or string.replace here, just convert that string to a raw string:

>>> strs = r"C:\Users\Josh\Desktop\20130216"
^
|
notice the 'r'

Below is the repr version of the above string, that's why you're seeing \\ here.
But, in fact the actual string contains just '\' not \\.

>>> strs
'C:\\Users\\Josh\\Desktop\\20130216'

>>> s = r"f\o"
>>> s #repr representation
'f\\o'
>>> len(s) #length is 3, as there's only one `'\'`
3

But when you're going to print this string you'll not get '\\' in the output.

>>> print strs
C:\Users\Josh\Desktop\20130216

If you want the string to show '\\' during print then use str.replace:

>>> new_strs = strs.replace('\\','\\\\')
>>> print new_strs
C:\\Users\\Josh\\Desktop\\20130216

repr version will now show \\\\:

>>> new_strs
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'


Related Topics



Leave a reply



Submit