String replaceAll doesn't like commas

Discussion in 'Java' started by O.B., Jan 31, 2006.

  1. O.B.

    O.B. Guest

    Why doesn't the following turn "Bubba, Inc." into "Bubba\, Inc."?

    String test = "Bubba, Inc.";
    test = test.replaceAll(",", "\\,");
     
    O.B., Jan 31, 2006
    #1
    1. Advertisements

  2. O.B.

    Stefan Ram Guest

    Stefan Ram, Jan 31, 2006
    #2
    1. Advertisements

  3. O.B.

    O.B. Guest

    O.B., Jan 31, 2006
    #3
  4. O.B.

    George Guest

    Try this:

    test = test.replaceAll(",", "\\\\,");
     
    George, Jan 31, 2006
    #4
  5. O.B.

    mikm Guest

    Change "\\," to "\\\\,"
     
    mikm, Jan 31, 2006
    #5
  6. The double quotes eat one backslash. The regex parser eats the other.
    Try "\\\\,".
     
    Jeffrey Schwab, Jan 31, 2006
    #6
  7. O.B.

    Roedy Green Guest

    Roedy Green, Jan 31, 2006
    #7
  8. O.B.

    Roedy Green Guest

    Roedy Green, Jan 31, 2006
    #8
  9. O.B.

    Roedy Green Guest

    see http://mindprod.com/jgloss/string.html#REPLACE
     
    Roedy Green, Jan 31, 2006
    #9
  10. O.B.

    Alan Krueger Guest

    It gets really fun when you want to quote backslashes in a string with
    an additional backslash:

    someString.replaceAll("\\\\", "\\\\\\\\");

    That's a lot of backslashes.
     
    Alan Krueger, Jan 31, 2006
    #10
  11. O.B.

    Stefan Ram Guest

    class String
    { final java.lang.String string;
    public String( final java.lang.String string )
    { this.string = string; }
    public java.lang.String replaceAll
    ( final java.lang.String search,
    final java.lang.String replace )
    { return this.string.replaceAll
    ( java.util.regex.Pattern.quote( search ),
    java.util.regex.Matcher.quoteReplacement( replace )); }}
    public class Main
    { public static void main( final java.lang.String[] args )
    { java.lang.System.out.println
    ( new String( "a\\b" ).replaceAll( "\\", "\\\\" )); }}
     
    Stefan Ram, Jan 31, 2006
    #11
  12. O.B.

    Alan Krueger Guest

    Some of us don't have the pleasure of being able to target a 1.5 JRE/JDK
    yet.
     
    Alan Krueger, Feb 1, 2006
    #12
    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.