aspose file tools*
The moose likes Beginning Java and the fly likes Replace all Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Replace all "." in a string" Watch "Replace all "." in a string" New topic
Author

Replace all "." in a string

Nirmal Mekala Kumar
Ranch Hand

Joined: Aug 27, 2005
Posts: 63
hi,
I have to replace all occurances of "." in a String with another character. Problem is replace and replaceAll methods expect regex. But "." has different meaning in regex. Also I cannot use an escape sequence as \. is not a valid escape sequence.
Currently I'm doing it in the crudest way possible ( using char[]). Is there any simpler way of doing this.


Nirmal Kumar<br />If you have to aim, aim for the moon. Even if you miss you will land among the stars
Srikanth Ramu
Ranch Hand

Joined: Feb 20, 2007
Posts: 76
use double slash "\\."
Nirmal Mekala Kumar
Ranch Hand

Joined: Aug 27, 2005
Posts: 63
sorry that doesn't work:



output::
before replace=10.91.102.54
after replace=10.91.102.54
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3681
    
  16
First of all, Strings are immutable, so the String referenced by str is not changed. replaceAll returns a new String.
Secondly, '\' is a special character in both regex and Java strings, so you need to escape the '\'s as well.
Try

[ March 26, 2007: Message edited by: Joanne Neal ]

Joanne
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

Secondly, '\' is a special character in both regex and Java strings, so you need to escape the '\'s as well.


Actually, "\\." is correct. You actually want the special meaning in the regex, as it is being used to escape the ".".

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Nirmal Mekala Kumar
Ranch Hand

Joined: Aug 27, 2005
Posts: 63
Thanks guys. I understood what stupid mistake i was doing. Sorry for that.
Alan Moore
Ranch Hand

Joined: May 06, 2004
Posts: 262
By the way, there are two replace() methods, and neither of them takes a regex argument. You could use either of them: The second version, replace(CharSequence,CharSequence), was added in JDK 1.5.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Replace all "." in a string