aspose file tools*
The moose likes Java in General and the fly likes String replace Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "String replace" Watch "String replace" New topic
Author

String replace

Swastik Dey
Rancher

Joined: Jan 08, 2009
Posts: 1398
    
    6

I have the following code snippet to replace a string, but it's not working.



Swastik
James Sabre
Ranch Hand

Joined: Sep 07, 2004
Posts: 781

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.


Retired horse trader.
 Note: double-underline links may be advertisements automatically added by this site and are probably not endorsed by me.
Raymond Tong
Ranch Hand

Joined: Aug 15, 2010
Posts: 230
    
    2

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

Joined: Sep 07, 2004
Posts: 781

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

Joined: Oct 27, 2005
Posts: 19543
    
  16

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: String replace
 
Similar Threads
javascript confirm pop up
String replace function
java.util.regex.PatternSyntax Exception
javascript confirm() function issue in IE 9
Return string from javascript function and display in text area.