Replacing backslash by another symbol in escape symbol - java

I have string some_text\1\12\3. Need to get string some_text.1.12.3, i. e. replace \ by .. The problem is that Java interprets \1 as one symbol (escape-symbol). And actually I need to replace part of escape-symbol.

It sounds like all you're missing is the knowledge of how to escape the backslash in a Java string literal - which is a matter of doubling the backslash:
String replaced = original.replace('\\', '.');
On the other hand, it's not clear where your text is coming from or going to anyway - the \1 part would only be relevant if it's being processed as part of a text literal. If you're actually trying to create a string of "some_text\1\12\3" in Java source code to start with, you'd want:
String withBackslashes = "some_text\\1\\12\\3";
Note that the actual text of the string that withBackslashes refers to only has three backslashes, not six. It's only the source code that needs them doubling. At that point, the replacement code at the top would replace the backslashes with dots.

This will do the job:
str = str.replace('\\', '.');

Related

Java Regex Escape Characters

I'm learning Regex, and running into trouble in the implementation.
I found the RegexTestHarness on the Java Tutorials, and running it, the following string correctly identifies my pattern:
[\d|\s][\d]\.
(My pattern is any double digit, or any single digit preceded by a space, followed by a period.)
That string is obtained by this line in the code:
Pattern pattern =
Pattern.compile(console.readLine("%nEnter your regex: "));
When I try to write a simple class in Eclipse, it tells me the escape sequences are invalid, and won't compile unless I change the string to:
[\\d|\\s][\\d]\\.
In my class I'm using`Pattern pattern = Pattern.compile();
When I put this string back into the TestHarness it doesn't find the correct matches.
Can someone tell me which one is correct? Is the difference in some formatting from console.readLine()?
\ is special character in String literals "...". It is used to escape other special characters, or to create characters like \n \r \t.
To create \ character in string literal which can be used in regex engine you need to escape it by adding another \ before it (just like you do in regex when you need to escape its metacharacters like dot \.). So String representing \ will look like "\\".
This problem doesn't exist when you are reading data from user, because you are already reading literals, so even if user will write in console \n it will be interpreted as two characters \ and n.
Also there is no point in adding | inside class character [...] unless your intention is to make that class also match | character, remember that [abc] is the same as (a|b|c) so there is no need for | in "[\\d|\\s]".
If you want to represent a backslash in a Java string literal you need to escape it with another backslash, so the string literal "\\s" is two characters, \ and s. This means that to represent the regular expression [\d\s][\d]\. in a Java string literal you would use "[\\d\\s][\\d]\\.".
Note that I also made a slight modification to your regular expression, [\d|\s] will match a digit, whitespace, or the literal | character. You just want [\d\s]. A character class already means "match one of these", since you don't need the | for alternation within a character class it loses its special meaning.
My pattern is any double digit or single digit preceded by a space, followed by a period.)
Correct regex will be:
Pattern pattern = Pattern.compile("(\\s\\d|\\d{2})\\.");
Also if you're getting regex string from user input then your should call:
Pattern.quote(useInputRegex);
To escape all the regex special characters.
Also you double escaping because 1 escape is handled by String class and 2nd one is passed on to regex engine.
What is happening is that escape sequences are being evaluated twice. Once for java, and then once for your regex.
the result is that you need to escape the escape character, when you use a regex escape sequence.
for instance, if you needed a digit, you'd use
"\\d"

Remove escape char ' \' from string in java

I have to remove \ from the string.
My String is "SEPIMOCO EUROPE\119"
I tried replace, indexOf, Pattern but I am not able to remove this \ from this string
String strconst="SEPIMOCO EUROPE\119";
System.out.println(strconst.replace("\\", " ")); // Gives SEPIMOCO EUROPE 9
System.out.println(strconst.replace("\\\\", " ")); // Gives SEPIMOCO EUROPE 9
System.out.println(strconst.indexOf("\\",0)); //Gives -1
Any solutions for this ?
Your string doesn't actually contain a backslash. This part: "\11" is treated as an octal escape sequence (so it's really a tab - U+0009). If you really want a backslash, you need:
String strconst="SEPIMOCO EUROPE\\119";
It's not really clear where you're getting your input data from or what you're trying to achieve, but that explains everything you're seeing at the moment.
You have to distinguish between the string literal, i.e. the thing you write in your source code, enclosed with double quotes, and the string value it represents. When turning the former into the latter, escape sequences are interpreted, causing a difference between these two.
Stripping from string literals
\11 in the literal represents the character with octal value 11, i.e. a tab character, in the actual string value. \11 is equivalent to \t.
There is no way to reliably obtain the escaped version of a string literal. In other words, you cannot know whether the source code contained \11 or \t, because that information isn't present in the class file any more. Therefore, if you wanted to “strip backslashes” from the sequence, you wouldn't know whether 11 or t was the correct replacement.
For this reason, you should try to fix the string literals, either to not include the backslashes if you don't want them at all, or to contain proper backslashes, by escaping them in the literal as well. \\ in a string literal gives a single \ in the string it expresses.
Runtime strings
As you comments to other answers indicate that you're actually receiving this string at runtime, I would expect the string to contain a real backslash instead of a tab character. Unless you employ some fancy input method which parses escape sequences, you will still have the raw backslash. In order to simulate that situation in testing code, you should include a real backslash in your string, i.e. a double backslash \\ in your string literal.
When you have a real backslash in your string, strconst.replace("\\", " ") should do what you want it to do:
String strconst="SEPIMOCO EUROPE\\119";
System.out.println(strconst.replace("\\", " ")); // Gives SEPIMOCO EUROPE 119
Where does your String come from? If you declare it like in the example you will want to add another escaping backslash before the one you have there.

String.replaceAll(...) of Java not working for \\ and \

I want to convert the directory path from:
C:\Users\Host\Desktop\picture.jpg
to
C:\\Users\\Host\\Desktop\\picture.jpg
I am using replaceAll() function and other replace functions but they do not work.
How can I do this?
I have printed the statement , it gives me the one which i wanted ie
C:\Users\Host\Desktop\picture.jpg
but now when i pass this variable to open the file, i get this exception why?
java.io.FileNotFoundException: C:\Users\Host\Desktop\picture.jpg
EDIT: Changed from replaceAll to replace - you don't need a regex here, so don't use one. (It was a really poor design decision on the part of the Java API team, IMO.)
My guess (as you haven't provided enough information) is that you're doing something like:
text.replace("\\", "\\\\");
Strings are immutable in Java, so you need to use the return value, e.g.
String newText = oldText.replace("\\", "\\\\");
If that doesn't answer your question, please provide more information.
(I'd also suggest that usually you shouldn't be doing this yourself anyway - if this is to include the information in something like a JSON response, I'd expect the wider library to perform escaping for you.)
Note that the doubling is required as \ is an escape character for Java string (and character) literals. Note that as replace doesn't treat the inputs as regular expression patterns, there's no need to perform further doubling, unlike replaceAll.
EDIT: You're now getting a FileNotFoundException because there isn't a filename with double backslashes in - what made you think there was? If you want it as a valid filename, why are you doubling the backslashes?
You have to use :
String t2 = t1.replaceAll("\\\\", "\\\\\\\\");
or (without pattern) :
String t2 = t1.replace("\\", "\\\\");
Each "\" has to be preceeded by an other "\". But it's also true for the preceeding "\" so you have to write four backslashes each time you want one in regex.
In strings \ is bydefault used as escape character therefore in order to select "\" in a string you have to use "\" and for "\" (i.e blackslack two times) use "\\". This will solve your problem and thos will also apply to other symbols also like "
Two explanations:
1. Replace double backslashes to one (not what you asked)
You have to escape the backslash by backslashes. Like this:
String newPath = oldPath.replaceAll("\\\\\\\\", "\\");
The first parameter needs to be escaped twice. Once for the Java Compiler and once because you use regular expressions. So you want to replace two backslashes by one. So, since we have to escape a backslash add one backslash. Now you have \\. This will be compiled to \. BUT!! you have to escape the backslash once again because the first parameter of the replaceAll method uses regular expressions. So to escape it, add a backslash, but that backslash needs to be escaped, so we get \\\\. These for backslashes represents one backslash in the regex. But you want to replace the double backslash to one. So use 8 backslashes.
The second parameter of the replaceAll method isn't using regular expressions, but it has to be escaped as well. So, you need to escape it once for the Java Compiler and once for the replace method: \\\\. This is compiled to two backslashes, which are being interpreted as 1 backslash in the replaceAll method.
2. Replace single backslash to a pair of backslashes (what you asked)
String newPath = oldPath.replaceAll("\\\\", "\\\\\\\\");
Same logic as above.
3. Use replace() instead of replaceAll().
String newPath = oldPath.replace("\\", "\\\\");
The difference is that the replace() method doesn't use regular expressions, so you don't have to escape every backslash twice for the first parameter.
Hopefully, I explained well...
-- Edit: Fixed error, as pointed out by xehpuk --

Illegal escape character error in Java regex

I've read the manual, and at the end there was an exercise:
Use a backreference to write an expression that will match a person's name only if that person's first name and last name are the same.
I've written the next program http://pastebin.com/YkuUuP5M
But when I compile it, I'm getting an error:
PersonName.java:18: illegal escape character
p = Pattern.compile("([A-Z][a-zA-Z]+)\s+\1");
^
If I rewrite 18 line in this way:
pattern = Pattern.compile(console.readLine("%nEnter your regex: "));
and write the pattern in the console, then the program works fine. Why I can't use the pattern as in the 1st program case and is there some way to fix it?
You want to get this text into a string:
([A-Z][a-zA-Z]+)\s+\1
However, \ in a string literal in Java source code is the character used for escaping (e.g. "\t" for tab). Therefore you need to use "\" in a string literal to end up with a single backslash in the resulting string. So you want:
"([A-Z][a-zA-Z]+)\\s+\\1"
Note that there's nothing regular-expression-specific to this. Any time you want to express a string containing a backslash in a Java string literal, you'll need to escape that backslash. Regular expressions and Windows filenames are just the most common cases for that.

String replace a Backslash

How can I do a string replace of a back slash.
Input Source String:
sSource = "http://www.example.com\/value";
In the above String I want to replace "\/" with a "/";
Expected ouput after replace:
sSource = "http://www.example.com/value";
I get the Source String from a third party, therefore I have control over the format of the String.
This is what I have tried
Trial 1:
sSource.replaceAll("\\", "/");
Exception
Unexpected internal error near index 1
\
Trial 2:
sSource.replaceAll("\\/", "/");
No Exception, but does not do the required replace. Does not do anything.
Trial 3:
sVideoURL.replace("\\", "/");
No Exception, but does not do the required replace. Does not do anything.
sSource = sSource.replace("\\/", "/");
String is immutable - each method you invoke on it does not change its state. It returns a new instance holding the new state instead. So you have to assign the new value to a variable (it can be the same variable)
replaceAll(..) uses regex. You don't need that.
Try replaceAll("\\\\", "") or replaceAll("\\\\/", "/").
The problem here is that a backslash is (1) an escape chararacter in Java string literals, and (2) an escape character in regular expressions – each of this uses need doubling the character, in effect needing 4 \ in row.
Of course, as Bozho said, you need to do something with the result (assign it to some variable) and not throw it away. And in this case the non-regex variant is better.
Try
sSource = sSource.replaceAll("\\\\", "");
Edit : Ok even in stackoverflow there is backslash escape... You need to have four backslashes in your replaceAll first String argument...
The reason of this is because backslash is considered as an escape character for special characters (like \n for instance).
Moreover replaceAll first arg is a regular expression that also use backslash as escape sequence.
So for the regular expression you need to pass 2 backslash. To pass those two backslashes by a java String to the replaceAll, you also need to escape both backslashes.
That drives you to have four backslashes for your expression! That's the beauty of regex in java ;)
s.replaceAll ("\\\\", "");
You need to mask a backslash in your source, and for regex, you need to mask it again, so for every backslash you need two, which ends in 4.
But
s = "http://www.example.com\\/value";
needs two backslashes in source as well.
This will replace backslashes with forward slashes in the string:
source = source.replace('\\','/');
you have to do
sSource.replaceAll("\\\\/", "/");
because the backshlash should be escaped twice one for string in source one in regular expression
To Replace backslash at particular location:
if ((stringValue.contains("\\"))&&(stringValue.indexOf("\\", location-1)==(location-1))) {
stringValue=stringValue.substring(0,location-1);
}
sSource = StringUtils.replace(sSource, "\\/", "/")

Categories

Resources