Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Replace all "." in a string

 
Nirmal Mekala Kumar
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Srikanth Ramu
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
use double slash "\\."
 
Nirmal Mekala Kumar
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry that doesn't work:



output::
before replace=10.91.102.54
after replace=10.91.102.54
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Henry Wong
author
Marshal
Pie
Posts: 20880
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Nirmal Mekala Kumar
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys. I understood what stupid mistake i was doing. Sorry for that.
 
Alan Moore
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic