String replaceAll doesn't like commas

O

O.B.

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

String test = "Bubba, Inc.";
test = test.replaceAll(",", "\\,");
 
G

George

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

String test = "Bubba, Inc.";
test = test.replaceAll(",", "\\,");

Try this:

test = test.replaceAll(",", "\\\\,");
 
J

Jeffrey Schwab

O.B. said:
Why doesn't the following turn "Bubba, Inc." into "Bubba\, Inc."?

String test = "Bubba, Inc.";
test = test.replaceAll(",", "\\,");

The double quotes eat one backslash. The regex parser eats the other.
Try "\\\\,".
 
A

Alan Krueger

Jeffrey said:
The double quotes eat one backslash. The regex parser eats the other.
Try "\\\\,".

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.
 
S

Stefan Ram

Alan Krueger said:
someString.replaceAll("\\\\", "\\\\\\\\");
That's a lot of backslashes.

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( "\\", "\\\\" )); }}
 
A

Alan Krueger

Stefan said:
{ return this.string.replaceAll
( java.util.regex.Pattern.quote( search ),
java.util.regex.Matcher.quoteReplacement( replace )); }}

Some of us don't have the pleasure of being able to target a 1.5 JRE/JDK
yet.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top