Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String ReplaceAll

 
manoj kumar jena
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
System.out.println("12.0".replaceAll(".0",""));

The above line prints 12 but the following line prints a blank string, why? it should print 10.
:!:
System.out.println("10.0".replaceAll(".0",""));
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
manoj kumar jena wrote:System.out.println("12.0".replaceAll(".0",""));

The above line prints 12 but the following line prints a blank string, why? it should print 10.
:!:
System.out.println("10.0".replaceAll(".0",""));



replaceAll(regex,replacementString); this function uses regular expression for matching.
For ".0" : dot means any character in regular expression, 0 means 0, so regex engine will try to find anycharacter ending with 0.
In first try it will find 10--------> 1 character ending with 0
in Second try it will find .0------> . character ending with 0.
 
Henry Wong
author
Marshal
Pie
Posts: 20892
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And as a side note... the correct regex for what you want is...



Henry
 
Bauke Scholtz
Ranch Hand
Posts: 2458
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you aren't going to take benefit from regexps, but just want to do a replace of the exact plain vanilla value, just use String#replace() instead. Requires at least Java 1.5 though.
 
manoj kumar jena
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much to all of you for your immediate and valuable response
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic