tags:

views:

142

answers:

3

In Java, I want to replace all * characters with \*.

Example: Text: select * from blah

Result: select \\* from blah

public static void main(String[] args) {
    String test = "select * from blah";
    test = test.replaceAll("*", "\\*");
    System.out.println(test);
}

This does not work, nor does adding a escape backslash.

+6  A: 

I figured it out

    String test = "select * from blah *asdf";
    test = test.replaceAll("\\*", "\\\\*");
    System.out.println(test);
Tim
test = test.replaceAll(@"\*", @"\\*"); I hate \\ personally, and prefer to use string literals.
WernerCD
@WernerCD: I've never seen that. What syntax is that?
Thilo
@WernerCD: Looks like C# not Java to me.
Richard Cook
If you've discovered your own solution, you should accept this as the answer to your question.
JoshD
@JoshD — SO forces you to wait (three days, IIRC) before accepting your own answer.
Ben Blank
@WernerCD: `replaceAll()` is Java, but `@""` is a C# verbatim string literal--Java has nothing like them.
Alan Moore
Ahh... Sorry... thought it was C#. My bad :) Yeah... that's C#, I'm surprised Java has nothing like it... It's late and my brain is mush.
WernerCD
This works, but it is overkill. There's no need to use regex for simple String replacement.
seanizer
A: 

For those of you keeping score at home, and since understanding the answer may be helpful to someone else...

String test = "select * from blah *asdf";
test = test.replaceAll("\\*", "\\\\*");
System.out.println(test);

works because you must escape the special character * in order to make the regular expression happy. However, \ is a special character in a Java string, so when building this regex in Java, you must also escape the \, hence \\*.

This frequently leads to what amounts to double-escapes when putting together regexes in Java strings.

RonU
+2  A: 

You don't need any regex functionality for this, so you should use the non-regex version String.replace(CharSequence, CharSequence):

String test = "select * from blah *asdf";
test = test.replace("*", "\\*");
System.out.println(test);
seanizer