Tuesday, May 12, 2009

String.replaceAll not working, solution here

Sometime we get Exception in thread "main" java.util.regex.PatternSyntaxException during String.replaceAll() using.
When I used this code :

public void replaceString(String path){
System.out.println("Original Path :: "+path);
String ret = path.replaceAll("\\","/");
System.out.println("Return :: "+ret);
}
I got this exception
Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1.


So for my project I am using this below custome method by the replaceAll method.


public void replaceString(String path){
System.out.println("Original Path :: "+path);
String ret = replaceAllString(path,"\\","/");
System.out.println("Return :: "+ret);
//return ret;
}
public String replaceAllString(String strOrig, String strFind, String strReplace) {
if(strOrig == null) {
return null;
}
StringBuffer sb = new StringBuffer(strOrig);
String toReplace = "";
if (strReplace == null) toReplace = "";
else toReplace = strReplace;
int pos = strOrig.length();
while (pos > -1) {
pos = strOrig.lastIndexOf(strFind, pos);
if (pos > -1) sb.replace(pos, pos+strFind.length(), toReplace);
pos = pos - strFind.length();
}
return sb.toString();
}

Its working fine for my project.

8 comments:

  1. Binod,
    “\\”, the first parameter in replaceAll is taken as “\” , since the first slash is just an escape character. But we actually need to have two slashes continuously so “\\\\” will do the purpose. For the above case, path.replaceAll("\\\\","/") will work perfectly.

    Happy coding. !!

    ReplyDelete
  2. I also feel some time that String.replaceAll() method does not work properly. This code is really very useful.

    Thanks.
    John

    ReplyDelete
  3. Sir,
    i was facing the same problem but ur code help me lot and my problem is solved.
    I need another help

    I want to send message to mobile from my windows based java application software can u plz help me by giving me idea and helping me by code.

    I also want to search some topics from google using my windows application software so if u plz help me by sending the idea and code then i shall be very glad to you.
    thanking You.

    my mail id is : molla_2006@yahoo.co.in

    ReplyDelete
  4. thanks Binod. Your code is very helpful to me. One thing to note is that:
    pos = pos - strFind.length();
    is a bit too "aggressive" for my task because I have back-to-back match pattern in the string. So I change it to:
    pos --;

    ReplyDelete
  5. Thanks for doing this, and sharing in this way. Your code is very useful in my own application.

    ReplyDelete
  6. Thanks for the code but Veeru's way is simple and also reduces all hassles.

    ReplyDelete
  7. this code really useful .
    good job.

    ReplyDelete

Please put your feedback or your any question related to this blog. Thanks.