File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes How to get or replace the backslash in Java string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to get or replace the backslash in Java string" Watch "How to get or replace the backslash in Java string" New topic
Author

How to get or replace the backslash in Java string

Sky Loi
Ranch Hand

Joined: Oct 06, 2008
Posts: 65
I try the followings:
System.out.println("12345\6"); // it get special char output like '12345'

I want to get or check this backslash by substring(..), charAt(..) or regx functions but they does not work. Is there any way to make it? Many thanks.



Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18847
    
  40

System.out.println("12345\6"); // it get special char output like '12345'


This is because the backslash has special meaning in a string literal. If you want an actual backslash, you will need to escape it -- like so...



In your example, there isn't a backslash in the string... as showned by the printout.



I want to get or check this backslash by substring(..), charAt(..) or regx functions but they does not work. Is there any way to make it? Many thanks.


First of all, I am not sure what you are asking. Second, I don't know how it related to the previous statement.

Henry

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Sky Loi
Ranch Hand

Joined: Oct 06, 2008
Posts: 65
Hi, Henry, thanks for quick reply.

I am doing some codes to validate a string not to include backslash "\". For example, user input "12345\6" and I have to check if it contains backslash. I try the followings but they does not work:

loop check:
for (int i=0; i<inputString.length(); i++){
char charValue = inputString.charAt(i);
if (charValue=='\\'){
return false;
}
}

or regx check
if (!Pattern.matches("[^\\\\]+", inputString)) return false;



>
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18847
    
  40

I am doing some codes to validate a string not to include backslash "\". For example, user input "12345\6" and I have to check if it contains backslash. I try the followings but they does not work:


If the user actually inputted the data, as you say, then it should work. If however, you are testing it with a string literal, then it won't work. The string literal will treat the backslash as a escape character, and the number following defines the ASCII of the specified character. So, in that case, there isn't any backslash in the string.

Henry
Mikko Kohtamäki
Ranch Hand

Joined: Dec 13, 2008
Posts: 112
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to get or replace the backslash in Java string