This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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 Murach's Java Servlets and JSP this week in the Servlets 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: 3418
    
  12
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: 18507
    
  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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Replace all "." in a string
 
Similar Threads
why java doesnt allow "\" ?
XML with Regular Expression Replaced Twice -- Wrongly
Regex splitting on carat symbol
When "\'something'" or "\\'something'" will not compile
Escaping Stuff in a String