String replaceAll problem

Discussion in 'Java' started by Muhammad Ali, Apr 13, 2007.

  1. Muhammad Ali

    Muhammad Ali Guest

    Hi,

    I have string

    String s = "Hello \"World\"";

    when i print this on console, it prints

    Hello "World"

    It works fine. Now what i want to is to print

    Hello \"World\"

    Which means i have to replace the quotes (") with (\\) and then a
    quote so that i may get a quote in output. so i used replaceAll method

    System.out.println(s.replaceAll("\"", "\\\""));

    But to my astonish, it prints out

    Hello "World".

    I wondered and then tried to do it again with

    System.out.println(s.replaceAll("\"", "\\\\\""));

    Now i was able to see the desired outout i.e; Hello \"World\"

    But why i have to use 5 back slashes instead of 3 which were according
    to the logic of "backsequences"?? I have seen the replaceAll method
    and it is using the pattern matching in it.

    If i try to replace the string using simple "replace" method it works
    fine; i.e i don't have to use 5 backslashes, i use only 3 (according
    to logic). Can someone explain why i have to use 5 slasheds in
    replaceAll.
     
    Muhammad Ali, Apr 13, 2007
    #1
    1. Advertisements

  2. Because '\' has a special meaning in a regex. Actually you have to
    escape the '\' TWO TIMES when using it in a regex - first time to not
    be interpreted as a special character in the Java String literal,
    second time to not be interpreted as a special character in the
    Regex :)

    I think I have read this somewhere in the Java API entry dealing with
    Regexes some time ago. You should check there for more details.

    /philipp

    Btw.: this is one of the many reasons why I really /hate/ regex :-/
     
    Philipp Leitner, Apr 13, 2007
    #2
    1. Advertisements

  3. Muhammad Ali

    Guest Guest

    now i using jbuilder7 and need newer version like what you using, can
    you tell me how can i get it or if i can downlod from net.

    thank you
     
    Guest, Apr 14, 2007
    #3
  4. "=?utf-8?B?2KfZhNi12KjYp9i6?=" <> burped up
    warm pablum in
    Why Soitainly! Download free versions from:
    http://www.codegear.com/Downloads/TrialandFreeVersions/JBuilder/
    tabid/143/Default.aspx for non-commercial use.
     
    Tris Orendorff, Apr 14, 2007
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.