I have a string.
String invalid = "backslash escaping as <>:;%+\/"."
I received an error message telling me to add \ to escape the sequence.
When I try to write this in Java I know that backslash needs to be escaped as \\. So I wrote it as:
String invalid = "backslash escaping as <>:;%+\\/\"."
Now this displays as backslash escaping as <>:;%+\\/".
The backslash is not escaping. How do I get only one backslash?
I don't find a problem with your modification. This runs as expected:
String invalid = "backslash escaping as <>:;%+\\/\".";
System.out.println(invalid);
output:
backslash escaping as <>:;%+\/".
In your first example, you have a little problem:
\/".
Which I believe should be like this:
/\".
Because in the first way, you are closing the string before you want to. The part ." is out of the String.
Edit:
try writing the output to a file or to a JTextField or something and see what happens, your string is correct and if you compare your output with my output it is the same. It might be an issue with your debugger (weird, but possible).
The second string in your post is correctly displayed. There must be something wrong with the way in which you observe the output.
Just try the simplest thing possible:
Create a file named Escape.java and write this code into its contents:
public class Escape {
public static void main(String... args) {
String s = "backslash escaping as <>:;%+\\/\".";
System.out.println(s);
}
}
Open a whatever command line that your OS provides and go to the folder with the said source file.
Compile the source file:
javac Escape.java
And run the class file:
java -cp . Escape
It should give this output:
backslash escaping as <>:;%+\/".
...which is exactly what you want, I believe.
Related
I am parsing below string value into OData query through java code.
objects.put("EndDate", "\/Date(1441756800)\/";
How can i parse the /Date(1441756800)/ into a string in java.
I have tried with below :
objects.put("EndDate", ""\\""//"Date(1441756800)""\\""//"";
throws error:(
I never used OData so I may not understand your question correctly, but if you are asking how to write \/Date(1441756800)\/ as String then you need to escape \ as it is String special character (used for instance when escaping or when creating other special characters like line separators \n).
So try with "\\/Date(1441756800)\\/"
Try this - objects.put("EndDate", "'Date(1441756800)'";
I'm trying to build a Java regex to search a .txt file for a Windows formatted file path, however, due to the file path containing literal backslashes, my regex is failing.
The .txt file contains the line:
C\Windows\SysWOW64\ntdll.dll
However, some of the filenames in the text file are formatted like this:
C\Windows\SysWOW64\ntdll.dll (some developer stuff here...)
So I'm unable to use String.equals
To match this line, I'm using the regex:
filename = "C\\Windows\\SysWOW64\\ntdll.dll"
read = BufferedReader.readLine();
if (Pattern.compile(Pattern.quote(filename), Pattern.CASE_INSENSITIVE).matcher(read).find()) {
I've tried escaping the literal backslashes, using the replace method, i.e:
filename.replace("\\", "\\\\");
However, this is failing to find, I'm guessing this is because I need to further escape the backslashes after the Pattern has been built, I'm thinking I might need to escape upto an additional four backslashes, i.e:
Pattern.replaceAll("\\\\", "\\\\\\\\");
However, each time I try, the pattern doesn't get matched. I'm certain it's a problem with the backslashes, but I'm not sure where to do the replacement, or if there's a better way of building the pattern.
I think the problem is further being compounded as the replaceAll method also uses a regex, with means the pattern will have it's own backslashes in there, to deal with the case insensitivity.
Any input or advice would be appreciated.
Thanks
Seems like you're attempting to to a direct comparison of String against another. For exact matches, you could do (
if (read.equalsIgnoreCase(filename)) {
of simply
if (read.startsWith(filename)) {
Try this :
While reading each line from the file, replace '\' by '\\'.
Then :
String lLine = "C\\Windows\\SysWOW64\\ntdll.dll";
Pattern lPattern = Pattern.compile("C\\\\Windows\\\\SysWOW64\\\\ntdll\\.dll");
Matcher lMatcher = lPattern.matcher(lLine);
if(lMatcher.find()) {
System.out.println(lMatcher.group());
}
lLine = "C\\Windows\\SysWOW64\\ntdll.dll (some developer stuff here...)";
lMatcher = lPattern.matcher(lLine);
if(lMatcher.find()) {
System.out.println(lMatcher.group());
}
The correct usage will be:
String filename = "C\\Windows\\SysWOW64\\ntdll.dll";
String file = filename.replace('\\', ' ');
I have done my .java file that changes registry data. But I am getting "illegal escape character" error on the line where Runtime.getRuntime().exec exists. Where is my mistake ?
import java.util.*;
import java.applet.Applet;
import java.awt.*;
class test {
public static void main(String args[]) {
try {
Runtime.getRuntime().exec("REG ADD 'HKCU\Software\Microsoft\Internet Explorer\Main' /V 'Start Page' /D 'http://www.stackoverflow.com/' /F");
} catch (Exception e) {
System.out.println("Error ocured!");
}
}
}
You need to escape the backslashes used in your path.
String windowsPath = "\\Users\\FunkyGuy\\My Documents\\Hello.txt";
You need to escape \ with another \, so replace \ with \\ in your input string.
You need to escape the backslash characters in your registry path string:
"REG ADD `HKCU\\Software\\ ...
The backslash character has a special meaning in strings: it's used to introduce escape characters. if you want to use it literally in a string, then you'll need to escape it, by using a double-backslash.
Back slashes in Java are special "escape" characters, they provide the ability to include things like tabs \t and/or new lines \n and lots of other fun stuff.
Needless to say, you to to "escape" them as well by adding an addition \ character...
'HKCU\\Software\\Microsoft\\Internet Explorer\\Main'
On a side note. I would use ProcessBuilder or at the very least, the version of Runtime#exec that uses array arguments.
It will save a lot of hassle when it comes to dealing with spaces within command parameters, IMHO
Probably because you didn't escape the backslash in your string. Have a look at http://docs.oracle.com/javase/tutorial/java/data/characters.html for more information about proper escaping.
you need replace escape \ with \\
below code will work
Runtime.getRuntime().exec("REG ADD 'HKCU\\Software\\Microsoft\\Internet Explorer\\Main' /V 'Start Page' /D 'http://www.stackoverflow.com/' /F");
Trying to get a simple string replace to work using a Groovy script. Tried various things, including escaping strings in various ways, but can't figure it out.
String file ="C:\\Test\\Test1\\Test2\\Test3\\"
String afile = file.toString() println
"original string: " + afile
afile.replace("\\\\", "/")
afile.replaceAll("\\\\", "/") println
"replaced string: " + afile
This code results in:
original string: C:\Test\Test1\Test2\Test3\
replaced string: C:\Test\Test1\Test2\Test3\
----------------------------
The answer, as inspired by Sorrow, looks like this:
// first, replace backslashes
String afile = file.toString().replaceAll("\\\\", "/")
// then, convert backslash to forward slash
String fixed = afile.replaceAll("//", "/")
replace returns a different string. In Java Strings cannot be modified, so you need to assign the result of replacing to something, and print that out.
String other = afile.replaceAll("\\\\", "/")
println "replaced string: " + other
Edited: as Neftas pointed in the comment, \ is a special character in regex and thus have to be escaped twice.
In Groovy you can't even write \\ - it is "an unsupported escape sequence". So, all answers I see here are incorrect.
If you mean one backslash, you should write \\\\. So, changing backslashes to normal slashes will look as:
scriptPath = scriptPath.replaceAll("\\\\", "/")
If you want to replace pair backslashes, you should double the effort:
scriptPath = scriptPath.replaceAll("\\\\\\\\", "/")
Those lines are successfully used in the Gradle/Groovy script I have intentionally launched just now once more - just to be sure.
What is even more funny, to show these necessary eight backslashes "\\\\\\\\" in the normal text here on StackOverflow, I have to use sixteen of them! Sorry, I won't show you these sixteen, for I would need 32! And it will never end...
If you're working with paths, you're better off using the java.io.File object. It will automatically convert the given path to the correct operating-system dependant path.
For example, (on Windows):
String path = "C:\\Test\\Test1\\Test2\\Test3\\";
// Prints C:\Test\Test1\Test2\Test3
System.out.println(new File(path).getAbsolutePath());
path = "/Test/Test1/Test2/Test3/";
// Prints C:\Test\Test1\Test2\Test3
System.out.println(new File(path).getAbsolutePath());
1) afile.replace(...) doesn't modify the string you're calling it on, it just returns a new string.
2) The input strings (String file ="C:\\Test\\Test1\\Test2\Test3\\";), from Java's perspective, only contain single backslashes. The first backslash is the escape character, then the second backslash tells it that you actually want a backslash.
so
afile.replace("\\\\", "/");
afile.replaceAll("\\\\", "/");
should be...
afile = afile.replace("\\", "/");
afile = afile.replaceAll("\\", "/");
In Groovy you can use regex in this way as well:
afile = afile.replaceAll(/(\\)/, "/")
println("replaced string: "+ afile)
Note that (as Sorrow said) replaceAll returns the result, doesn't modify the string. So you need to assign to a var before printing.
String Object is immutable so if you call a method on string object that modifies it. It will always return a new string object(modified). So you need to store the result return by replaceAll() method into a String object.
As found here, the best candidate might be the static Matcher method:
Matcher.quoteReplacement( ... )
According to my experiments this doubles single backslashes. Despite the method name... and despite the slightly cryptic Javadoc: "Slashes ('\') and dollar signs ('$') will be given no special meaning"
I have a path called $SERVER/public_html/ab1/ab2/.
I want to change it so that instead of $SERVER it just replaces it with my user directory. So I do
path = path.replaceFirst("\\$SERVER", System.getProperty("user.dir"));
but when I run it, it removes my \ in the new string.
F:Programming ProjectsJava Project/public_html/ab1/ab2/
Pattern has a String quote(String) function that will help you for the first string and Matcher has String quoteReplacement(String) for the second:
path = path.replaceFirst(java.util.regex.Pattern.quote("$SERVER"), java.util.regex.Matcher.quoteReplacement(System.getProperty("user.dir")));
edit: the reason you have to escape anything is because the second string has the semantics of Matcher.appendReplacement which treats backslashes and dollars as escape next char and insert captured group resp.
from the doc:
Note that backslashes () and dollar
signs ($) in the replacement string
may cause the results to be different
than if it were being treated as a
literal replacement string. Dollar
signs may be treated as references to
captured subsequences as described
above, and backslashes are used to
escape literal characters in the
replacement string.
a more obvious solution is (be careful of the needed escaped with that backslash)
path = path.replaceFirst("\\$SERVER", System.getProperty("user.dir").replaceAll("\\\\","\\\\\\\\"));
Yea you are completly right. I am trying to figure out why it is happening so.
But at the moment the only think I can suggest is to go with such a solution.
public class RegExTest
{
public static void main(String[] args)
{
String path = "$SERVER/public_html/ab1/ab2";
System.out.println("path before="+path);
String user = System.getProperty("user.dir");
System.out.println("user="+user);
System.out.println("replaceFirst using user="+path.replaceFirst("\\$SERVER", user));
path = path.replaceFirst("\\$SERVER", "");
path = user +path;
System.out.println("path after="+path);
}
}
EDIT: ..Why it does that?
From what I see in the code of the method line 701 to 708 they must do it. They just skip them. As to the reason why they do it, I still am not sure.
EDIT2:
OK reading the doc for the method answers it all. They do it so they can interpret accordingly special characters. Thus when reading the replacement they spot a slash the algorithm assumes it can be a part of special character and in result skips it.
if (nextChar == '\\') {
cursor++;
nextChar = replacement.charAt(cursor);
result.append(nextChar);
cursor++;
} else if (nextChar == '$') {
// Skip past $
cursor++;
Ok so in Windows the default slashes look like so '\' whereas on *nix the slashes look like so '/' . The simplest way to get through this problem is to invoke the replace function with the following parameters '\\' and '/' . That way you path will have its slashes all facing the same way.