This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
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 replace

 
Swastik Dey
Rancher
Posts: 1603
5
Android Java Java ME
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the following code snippet to replace a string, but it's not working.

 
James Sabre
Ranch Hand
Posts: 781
Java Netbeans IDE Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first parameter to replaceAll() is a regular expression and in regular expressions the characters '(' ,')' and '*' are meta characters that have a special meaning. I suspect you just need to use the replace() method which takes the first argument literally.
 
Raymond Tong
Ranch Hand
Posts: 255
2
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Swastik Dey wrote:I have the following code snippet to replace a string, but it's not working.


As mentioned above, String.replaceAll treats the first argument string as regular expression.
If you want to replace ALL without regular expression, try with \Q..\E sequence.
http://www.regular-expressions.info/characters.html#qe
 
James Sabre
Ranch Hand
Posts: 781
Java Netbeans IDE Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Raymond Tong wrote:
If you want to replace ALL without regular expression, try with \Q..\E sequence.


That is absolutely true and I considered posting this information but the OP seems not to understand even the minimum about regular expressions since he obviously did not recognise the most fundamental meta characters. The conclusion is that the OP just wants to replace literally and then what is the point of going to the trouble of parsing a regular expression when the replace() method will achieve the same result?
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd use Pattern.quote instead of manually adding \Q and \E, but I'd prefer using replace over replaceAll unless you need to use a regex.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic